Why does this if statement always log true no matter how long pin actually is?
JavaScript
x
7
1
const pin = 1
2
3
if (pin.toString().length = 4 || 6) {
4
console.log(true);
5
}
6
//logs true
7
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.
JavaScript
1
2
1
pin.toString().length = 4
2
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:
JavaScript
1
6
1
const pin = 1;
2
3
if (pin.toString().length === 4 || pin.toString().length === 6) {
4
console.log(true);
5
}
6
This will never log true, because ‘1’.length === 1.