I noticed in Javascript, I have occasionally seen
var foo = bar && bar.getSomething()
I know it is probably similar to say:
var foo;
if(bar !== undefined) {
foo = bar.getSomething();
}
But it still makes me confused. Because to me, it is quite similar to a binary operation such as:
0100 & 0101 == 0100; //true
However, it is quite different on another hand, because for example, if bar is an object, and bar.getSomething() return an integer(saying 5 in the following example), and the code ends up as:
var foo = {baz : qux} && 5;
it obviously makes no sense to me.
So My question is that why in Javascript, people can code in this way? Is this an implementation of the binary operation in JS? What is the name of this coding practice? is there any performance benefit compared to the traditional way? Thanks
&&is the logical AND, not bitwise AND.is there any performance benefit compared to the traditional way?Most likely not, Javascript Engines are pretty smart these day, micro optimisations like this usually don't gain anything. The main use is just to make code shorter, it's basically saying keep executing from the left, until something returns false. You can chain them more than just 2, eg.. action1 && action2 && action3, if action2 returned false, action3 wouldn't get executed.ifstatement.