Variable assignment inside an 'if' condition in JavaScript

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

    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.

提交回复
热议问题