Frage

How does the below code execute?

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

OUTPUT

a=8
War es hilfreich?

Lösung

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.

Andere Tipps

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)

It is called operator precedence

(a=2 && (b=8))

In the above example. then results are evaluated against the main && sign.

(a=2 && (b=8)) evaluated to a = 2 && 8

So 2 && 8 return a = 8

You're setting (not comparing) a to 2 && (b=8). Since 2 is tru-ish the second half of the expression will be executed, i.e. a = true && (b = 8), i.e. a = (b = 8), i.e. a = 8.

Your statement is interpreted like

a = (2 && (b=8))

when you uses && statement, then last true statement value will be returned. Here (b=8) will becomes value 8 which is true and last statement.

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
    • the left hand expression 2 is evaluated which is truthy
    • the right hand expression b = 8 is evaluated (b becomes 8 and 8 is returned)
    • 8 is returned
  • a = 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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top