Loren Shqipognja Loren Shqipognja - 2 years ago 70
Javascript Question

Assignment operator inside if clause assigns value and performs check?

I noticed something whilst debugging my code.

console.log("it's 5 units long");

This not only makes the array size 5(assuming it performs the assignment every time) but it also performs the check in the if, resulting in a console output. Is this normal behaviour in Javascript and is this a valid shorthand for any real scenario?

Answer Source

The result of an assignment expression is the new value. Your code is equivalent to:

array.length = 5;
if (5) {
    console.log("it's 5 units long");

And 5 is a truthy value, so the condition passes.

The following values are always falsy:

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN (a special Number value meaning Not-a-Number!)

All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.

I can contrive scenarios where this would be useful, but generally, no, it's not useful. At the very least, it's bad style, and shouldn't be used even if it can be.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download