Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created June 21, 2011 00:49
Show Gist options
  • Save cowboy/1036978 to your computer and use it in GitHub Desktop.
Save cowboy/1036978 to your computer and use it in GitHub Desktop.
JavaScript: See what == what!
// 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
*/
@walkingeyerobot
Copy link

http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf - Section 11.9.3 explains this. Like you said, scary stuff.

@kflorence
Copy link

All good reasons to use === whenever possible.

@cowboy
Copy link
Author

cowboy commented Jun 23, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment