Variable assignment inside an 'if' condition in JavaScript

前端 未结 6 708
眼角桃花
眼角桃花 2020-12-29 19:59

How does the below code execute?

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

OUTPUT

a=8
6条回答
  •  渐次进展
    2020-12-29 20:13

    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.

提交回复
热议问题