var test = 2;
test === 2 && console.log('true');
This confuses me. I hadn't seen this before until the other day. The output of this will be true
in the console.
So how does this magic work?
var test = 2;
test === 2 && console.log('true');
This confuses me. I hadn't seen this before until the other day. The output of this will be true
in the console.
So how does this magic work?
This (mis)uses the boolean handling of JavaScript; because of the lazy evaluation of expressions,
console.log('true')
is only run, when someVar === 2
was previously evaluated as true
.
This behaviour is called Short-circuit evaluation.
By the way, this type of coding has legit use cases. My favourite is the use of configuration objects:
function (options) {
var options = options || {};
}
This way, the options object exists even if it was not given in as a parameter.
Actually, this code isn't valid:
var === 2 && console.log('true')
VM132:2 Uncaught SyntaxError: Unexpected token ===
You can try it yourself in the browser (i.e. in Chrome look for Developer Tools).
See http://jsfiddle.net/jcdxnte0/
EDIT:
The syntax x && y
means that both x
and y
need to be true. This means, that if x
is true, y
will get evaluated, and if x
is false, y
will not get evaluated (because x
was false, so both will never be true so why bother evaluating y
? - evaluation goes from left to right). In your case, x
is test === 2
, and y
is console.log(...)
.
it can be read as
if( test === 2 ){ console.log('true'); }
It works because (test === 2)
is an expression which resolves to a value.
It'll resolve to either true or false. JavaScript will then execute code after &&
only if the preceding expression returned true. (so false && console.log()
won't log anything).
Another fun way to abuse it and confuse other developers is the fact that assignment also returns a value, for example
var x = 0, y = 5;
(x = y) && console.log( 'x is now 5' );
in this case (x = y)
not only assigns the value of y
to x
, but also returns 5
which is truthy, so the console.log
gets evaluated. don't use this, please.
JavaScript evaluates the left part and, if it's true, executes the right part. You can do the opposite with the ||
operator.
It's also worth noting that the right part should be wrapped in parenthesis if it contains an assignment:
var foo;
true && (foo = "bar");
While it's perfectly valid, I'd recommend not using this syntax.