skip to Main Content
let foo;
foo = 1 === 1;
if ((foo = -5)) {
   console.log("Will always work");
} else {
   console.log("Will NEVER work");
}

I understand that the variable foo is set to be 1 === 1, so it is true. Then there is a condition in the second line.

How the condition is fulfilled so I get the first console.log printing? Why doesn’t it skip to the second printing? Is foo = -5 also true?

2

Answers


  1. Yes, foo = -5 is true because the assignment operator evaluates to -5 which is not zero.

    Login or Signup to reply.
  2. let statement lets you reassign variables so you assigned 1 to the variable then by if (foo = -5), you reassign the value -5 to the variable, so the condition will always be true.

    Assignment is not the same as comparison.

    = is assignment, but == and === are comparison.

    You should use if (foo === -5) if you want the variable’s value to be 1, therefore if (foo === -5) will be false, and it’ll skip to else aka the second part of console.log.

    See: Expressions and operators to learn more about assignment and comparison.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search