Variable assignment inside an 'if' condition in JavaScript

前端 未结 6 703
眼角桃花
眼角桃花 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:27

    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.

提交回复
热议问题