Oddities in JS comparisons
by Alon Rotem
HTML
The double-equal operator == forcefully <b>tries to cast</b> the compared objects.<br/>
The triple-equal operator === compares objects <b>as they are</b>.<br/><br/>
CSS
.gr {
background-color: #88DF33;
}
.rd {
background-color: pink;
}
input[type='button'] {
display: block;
margin: 10px;
padding: 2px;
min-width: 150px;
}
body {
font-family: verdana;
font-size: small;
}
JavaScript
function createButton(v1, v2){
var v1Str = (typeof(v1) === "string") ? ("'" + v1 + "'") : v1;
var v2Str = (typeof(v2) === "string") ? ("'" + v2 + "'") : v2;
var equalitiesAreEqual = ((v1 == v2) == (v1 === v2));
var newBtn = document.createElement('input');
newBtn.setAttribute('type','button');
newBtn.setAttribute('class',(equalitiesAreEqual)? "gr": "rd");
newBtn.setAttribute('value',v1Str + " == " + v2Str);
newBtn.onclick = function(){
alert("(" + v1Str + " == " + v2Str + ") = " + (v1 == v2) + "\n"
+ ((equalitiesAreEqual) ? "" : "\n --- but: ---\n\n")
+ "(" + v1Str + " === " + v2Str + ") = " + (v1 === v2));
};
document.body.appendChild(newBtn);
}
createButton ('', '0');
createButton (0, '');
createButton (0, '0');
createButton (true, '1');
createButton (false, '0');
createButton (false, 'false');
createButton (false, undefined);
createButton (false, null);
createButton (null, undefined);
createButton (' \t\r\n ', 0);
//primitive string value vs String object
createButton ('abc', new String('abc')); //not consistent
createButton ('abc', 'abc'); //both true
createButton (new String('abc'), new String('abc')); //both false
var a = [1,2,3];
var b = [1,2,3];
var c = a;
createButton (a, b); //both false (2 seperate objects)
createButton (a, c); //both true! (objects assigned to each other)
/*
//primitive literal string vs String object
//defining an extension method:
if (typeof String.prototype.isEqual!= 'function') {
String.prototype.isEqual = function (str){
return this.toUpperCase()==str.toUpperCase();
};
}
console.log("aaaa".isEqual);
console.log(new String("aaaa").isEqual);
*/