Monday, March 27, 2017

To compare or not to compare !

It is well known that null and undefined are unique in Javascript. However the following behavior was not known to me and hence the post. Basically null is coerced to 0 when using >, <, >=, <= operators but not when == operator is used. Quirky at its best :)


var counter = null;
var something = false;
if(something) {
counter += 1;
}
if(counter == 0) {
console.log("failed to update");
}
if(counter <= 0) {
console.log("print again the failure");
}
// if something is true this will be printed
if(counter > 0) {
console.log("successfully updated");
}