Reputation: 93
Let's take the code
var dumb = [1,2,3,4,5,6]
for (var x = 0; x < dumb.length; x++){
if (dumb[x] % 2) {
console.log(dumb[x]);
}
}
In the above program, it produces (1,3,5) But if the if statement was: (if dumb[x] % 2 === 0), it produces (2,4,6)
Why Does
if (dumb[x] % 2)
and
if (dumb[x] % 2 === 0)
produce difference results?
Upvotes: 1
Views: 45
Reputation: 12777
You're comparing the output of the modulo operator, vs the output of a boolean expression.
dumb[x] % 2
works out to a number, while
dumb[x] % 2 === 0
works out to a boolean, true or false.
If the first expression works out to 0, it'll be falsey, otherwise it'll be truthy.
Upvotes: 1
Reputation: 115538
In a conditional statement in JavaScript 0
is false
and all other numbers are true
.
if (dumb[x] % 2) // if the numbers is even, it's false because the remainder is 0.
and
if (dumb[x] % 2 === 0)
//if even it's true, because the remainder 0 which is what you are comparing it to.
Upvotes: 2