JavaScript – Variable Assignment Inside if Condition

javascriptoperators

How does the below code execute?

if(a=2 && (b=8))
{
    console.log(a)
}

OUTPUT

a=8

Best Answer

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.

Related Question