-3

Why does this if statement always log true no matter how long pin actually is?

const pin = 1

if (pin.toString().length = 4 || 6) {
  console.log(true);
}
//logs true

Edit: If a mod sees this, should I delete this question? I was very bad at javascript when I asked this.

NHerwich
  • 110
  • 15
  • 4
    Because `6` is always true. Go read up on _operator precendence_. – CBroe May 27 '21 at 10:44
  • 5
    You're missing two `=`. It should be `.length === 4`. Also 6 is always truthy. Try `pin.toString().length === 4 || pin.toString().length === 6`. – aside May 27 '21 at 10:44
  • 1
    It should be `pin.toString().length === 4 || pin.toString().length === 6` – Charchit Kapoor May 27 '21 at 10:45
  • Does this answer your question? [Or operator not working in IF statement Node.js](https://stackoverflow.com/questions/33089632/or-operator-not-working-in-if-statement-node-js) – Sebastian Simon May 27 '21 at 10:47
  • What is the actual purpose of this code? `(1).toString()` is `"1"`, so its length will neither be `4` nor `6`. If you want to test binary string length, I guess `pin.toString(2)` can be used, though the use case is weird. Simply `if([4, 6].includes(String(pin).length)){`…`}` should be enough, otherwise. – Sebastian Simon May 27 '21 at 10:49

1 Answers1

1

Both statements in your || (or) statement will resolve to true, so the log will always be called.

pin.toString().length = 4 

resolves to true because you're SETTING the length to 4 and then the check becomes 'is there a length' which is only falsy if the length === 0.

The second part of the equality is simply '6'. Any number that's not 0 is truthy, so will resolve to true.

You probably mean something like this:

const pin = 1;

if (pin.toString().length === 4 || pin.toString().length === 6) {
    console.log(true);
}

This will never log true, because '1'.length === 1.

Katinka Hesselink
  • 3,961
  • 4
  • 20
  • 26