Created
June 21, 2011 00:49
-
-
Save cowboy/1036978 to your computer and use it in GitHub Desktop.
JavaScript: See what == what!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This should do a pretty good job of iterating through the following array | |
// and logging any values that == each other. Beware, this is scary stuff! | |
// http://benalman.com/news/2010/11/schrecklichwissen-terrible-kno/ | |
var arr = [true, 123, {}, {a:1}, [], [0], [123], "hi", function foo(){}, | |
/re/, Infinity, false, 0, "", null, undefined, NaN]; | |
function pretty(v) { | |
return /^[os]/.test(typeof v) ? JSON.stringify(v) : String(v); | |
} | |
arr.forEach(function(v) { | |
var truthy = v ? "truthy" : "falsy"; | |
var eq = []; | |
arr.forEach(function(w) { | |
if ( v == w ) { eq.push(pretty(w)); } | |
}); | |
eq.length || eq.push("N/A"); | |
console.log("%s (%s) == %s", pretty(v), truthy, eq.join(", ")); | |
}); | |
/* | |
OUTPUT: | |
true (truthy) == true | |
123 (truthy) == 123, [123] | |
{} (truthy) == {} | |
{"a":1} (truthy) == {"a":1} | |
[] (truthy) == [], false, 0, "" | |
[0] (truthy) == [0], false, 0 | |
[123] (truthy) == 123, [123] | |
"hi" (truthy) == "hi" | |
function foo(){} (truthy) == function foo(){} | |
/re/ (truthy) == /re/ | |
Infinity (truthy) == Infinity | |
false (falsy) == [], [0], false, 0, "" | |
0 (falsy) == [], [0], false, 0, "" | |
"" (falsy) == [], false, 0, "" | |
null (falsy) == null, undefined | |
undefined (falsy) == null, undefined | |
NaN (falsy) == N/A | |
*/ |
All good reasons to use === whenever possible.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf - Section 11.9.3 explains this. Like you said, scary stuff.