Reputation: 1276
I have below Basic Javascript to reverse the number which work when I use
while (!no == 0)
But Doesn't work when I use
while (!no === 0)
I have tried in the console for parseInt(0)
which returns number
only and my no
is already number
so
why
===
is not working ,Can someone help and explain me better?
function findRepeated(number) {
var a, no, b, temp = 0;
no = parseInt(number);
while (!no == 0) {
a = no % 10;
no = parseInt(no / 10);
temp = temp * 10 + a;
}
return temp;
}
console.log(findRepeated(123));
Upvotes: 5
Views: 370
Reputation: 2134
!no
returns a boolean, it returns false, although the value of no is a number, adding the negate operator in front of any number will return a false, i.e. console.log(!123 === false)
. As you're probably aware, using ==
will convert the data type for you, where as using ===
will not.
I like the example of null and undefined.
While null == undefined
is true, null === undefined
is false, because the value null is a type of object, whereas the type of undefined is of course undefined.
console.log("test1: " + !123); // false
console.log("test2: " + (!123 === false)); // true
console.log("test3: " + (!123 == 0)); // true
console.log("test4: " + (!123 === 0)); // false
console.log("test5: " + (0 == false)); // true
console.log("test6: " + (0 === false)); // false
console.log("test7: " + (null == undefined)); // true
console.log("test8: " + (null === undefined)); // false
console.log("test9: " + typeof null); // object
console.log("test10: " + typeof undefined); // undefined
Upvotes: 4
Reputation: 72256
!no == 0
is not the same as !(no == 0)
. It is (!n) == 0
.
Similar, !no === 0
is (!no) === 0
.
This always evaluates to false
because !no
is a boolean and 0
is a number.
Values of different types are never ===
.
Read about the logical NOT operator, the comparison operators and operator precedence.
Upvotes: 8