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.
Advertisement
Answer
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.