How does the below code execute?
if(a=2 && (b=8))
{
console.log(a)
}
OUTPUT
a=8
It has nothing to do with the if statement, but:
if(a=2 && (b=8))
Here the last one, (b=8), actually returns 8 as assigning always returns the assigned value, so it's the same as writing
a = 2 && 8;
And 2 && 8 returns 8, as 2 is truthy, so it's the same as writing a = 8.
8 to b, but assigning will return the assigned value as well, so that's correct.It's generally a bad idea to do variable assignment inside of an if statement like that. However, in this particular case you're essentially doing this:
if(a = (2 && (b = 8)));
The (b = 8) part returns 8, so we can rewrite it as:
if(a = (2 && 8))
The && operator returns the value of the right hand side if the left hand side is considered true, so 2 && 8 returns 8, so we can rewrite again as:
if(a = 8)
To understand what is going on, refer to the operator precedence and associativity chart. The expression a = 2 && (b = 8) is evaluated as follows:
&& operator is evaluated before = since it has higher priority
2 is evaluated which is truthyb = 8 is evaluated (b becomes 8 and 8 is returned)8 is returneda = 8 is evaluated (a becomes 8 and 8 is returned)Finally, the if clause is tested for 8.
Note that 2 does not play any role in this example. However, if we use some falsy value then the result will be entirely different. In that case a will contain that falsy value and b will remain untouched.
b=8in parens but nota=2? It looks almost as if this is a trolling attempt.b=, why didn't you bother to check the value ofb? That would have given enough clues...b=8or you can simply say, to avoid error.a = (2 && (b=8)). This pretty much would have allowed to figure out the problem. At the very least I'd expect a minimal amount of debugging before posting a question on Stack Overflow