Variable assignment inside an 'if' condition in JavaScript

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

    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)
    

提交回复
热议问题