What is the difference between this statement
var X = X || {};
And this. They do the same thing? There is a performance difference?
var X = typeof X === "undefined" ? {} : X;
They're not the same.
The || will return the object when X is any possible falsy value.
The typeof check will only return {} if is X is undefined.
According to this test, the undefined check is nearly twice as fast. That's probably because no type casting is required.
In this case: var X = X || {} the X variable will be redefined if it's been declared but is falsy. So var X = 0; X = X || {}; would overwrite the 0 with an object.
Related
const add = (x=5, y=10) => console.log(x+y);
After we run the transpiler on this code, here is what the output would look like:
"use strict";
var add = function add() {
var x = arguments.length <= 0 || arguments[0] === undefined ?
5 : arguments[0];
var y = arguments.length <= 1 || arguments[1] === undefined ?
10 : arguments[1];
return console.log(x + y);
};
I got this snippet from Learning react book.
I have two question here
Can arguments.length be negative?
Does checking the second "||" condition be sufficient to check whether arguments[0] or arguments[1] is undefined?
Can arguments.length be negative?
No. How could you call a function and put a negative number of things between ( and )?!
Does checking the second condition be sufficient?
No. The function might be called with only one argument.
function bar(x=y, y=2) {
return [x, y];
}
bar();//uncaught reference: y is not defined
I can't understand why the above code will hit exception. If from other languages it make sense because flow of programs are important and we can't reference to y because y is not created yet and it would be resulted in compilation error. However this is JS, both x and y should equally be hoisted first and such reference shouldn't throw exception. I would expect the pseudo-code to be similar like below?
x=y
var x;
var y;
console.log(x,y); //undefined undefined (which is fine as no value but instead of throwing exception)
UPDATES:
function bar() {
var x = arguments.length >= 1 ? arguments[0] : y;
{
var y = arguments.length >= 2 ? arguments[1] : 2;
return [x, y];
}
}
console.log(bar());//[undefined, 2]
Your assumption is wrong, they're not hoisted like that. It's more like:
function bar() {
let x = arguments.length >= 1 ? arguments[0] : y;
{
let y = arguments.length >= 2 ? arguments[1] : 2;
return [x, y];
}
}
The scope of each variable default value only includes the variables to the left of it, not the variables to the right.
I obviously got something terribly wrong here so I'll appreciate any good 'ol advice.
How come that if I write
var x='';
var y="12345";
(y.substring(0, 3) === "000"||"999") ? x=1: x=0;
console.log (x, y.substring(0, 3));
The answer would be 1 "123"
instead of 0 "123"?
Thanks y'all!
First the ternary operator syntax is not how you use it normally and you'll have to make two comparisons instead of one.
var str = y.substring(0, 3);
x = (str === "000"|| str === "999") ? 1 : 0;
MDN
For condition ? expr1 : expr2
If condition is true, the operator returns the value of expr1;
otherwise, it returns the value of expr2.
The or operater works like this: a || b
Where each statement is isolated from eachother, basically you can make i more visible like this:
var c1 = y.substring(0, 3) === "000";
var c2 = "999";
if ( c1 || c2 ) { x = 1; } else { x = 0; };
See the problem here?
I would rewrite your statement so something like this:
x = ["000", "999"].indexOf(y.slice(0, 3)) > -1 ? 1 : 0;
Note how I'm using Array.prototype.indexOf to test multiply cases:
["000", "999"].indexOf(y.slice(0, 3)) // returns the index of the array or -1 if not in the array.
What is this javascript syntax?
parent[currentPart] = parent[currentPart] || {};
especially this part || {}
It is taken from this javascript code (at http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/)
// Creates a namespace
function namespace(namespaceString) {
var parts = namespaceString.split('.'),
parent = window,
currentPart = '';
var length = parts.length;
for (var i = 0; i < length; i++) {
currentPart = parts[i];
parent[currentPart] = parent[currentPart] || {};
parent = parent[currentPart];
}
return parent;
}
The || operator in javascript works a little differently than many other languages. In javascript, it evaluates to the first 'truthy' value, allowing a "fallthrough" sort of behavior.
Example:
var a = false;
var b = "asdf";
alert(a || b); //alert box with "asdf" since a was false
var c = true;
var d = "asdf";
var e = false;
alert(c || d || d); //alert box with true. d and e were never evaluated, so "asdf" isn't returned. This is called "short-circuiting" operation.
The && operator works similarly in that it evaluates to the first 'falsey' value or the last 'truthy' value if everything is true:
var a = true;
var b = "asdf";
alert(a && b); //alert box with "asdf"
alert(b && a): //alert box with true
var c = 6;
var d = 0;
alert(c && d); //alert box with 0
alert(d && c); //alert box with 0
In JS, logical operators (e.g. &&, ||) return a value, which, when part of an expression, can be used in an assignment.
Thus in the code below:
var a = false
, b = 'hello'
, c = (function() { return a || b })()
c is assigned the string 'hello', because || returns 'hello' to the return statement, which, in turn, returns it from the function and makes the assignment to c.
The definition of the || operator is:
expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2.
If parent[currentPart] does not exist, then the expression evaluates to an empty object ({}) and thus parent[currentPart] is initialized to that empty object. If it does exist, then it is left unchanged (that is, it is assigned to itself). The effect is to guarantee that parent[currentPart] always has a (non-falsy) value.
In the expression a = b || c, a will be set to b if b evaluates to true; otherwise, a will be set to c. This is often used because null and undefined both evaluate to false, so it's shorter than saying something like if (b == null) {a = c} else {a = b}.
Is there any value for what x === x returns false without NaN?
For example:
> x = 1
1
> x === x
true
> x = {}
{}
> x === x
true
> x = new Date()
Wed Nov 13 2013 15:44:22 GMT+0200 (EET)
> x === x
true
> x = NaN
NaN
> x === x
false
I see that the only value where x === x returns false is when isNaN(x) === true.
Is there another value of x for what x === x returns false? An official reference would be welcome!
The strict comparison between two equal non-NaN values will always be true (SLaks's answer correctly quotes the spec). However, it's possible for the expression x to change its value during the evaluation of the the equality. This can happen with property access when using accessor property descriptors (i.e., property getters):
foo = {};
Object.defineProperty(foo, "bar", {
get: function() {
return Math.random();
}
})
foo.bar === foo.bar; // false
If you do this for the global object window (or global in Node), then you can see the x === x comparison fail for a global-scope variable:
Object.defineProperty(window, "bar", {
get: function() {
return Math.random();
}
})
bar === bar; // false
The spec lists the exact rules for strict equality.
There are no other such cases, unless you count +0 and -0.
The SameValue algorithm (used for validating changes to read-only defined properties) has no such exceptions.