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