Skip to content

Instantly share code, notes, and snippets.

@fhemberger
Created May 12, 2012 09:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhemberger/2665360 to your computer and use it in GitHub Desktop.
Save fhemberger/2665360 to your computer and use it in GitHub Desktop.
Loose comparison with == in JavaScript
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
th, td {
text-align: center;
padding: 10px;
}
th { background-color: #f0f0f0; }
.true { background-color: #e0ffe0; }
.false { background-color: #ffe0e0; }
</style>
</head>
<body>
<h1>Loose comparison with == in JavaScript</h1>
<table></table>
<script>
var comparisons = [true, false, 1, 0, -1, "1", "0", "-1", null, undefined, [], {}, ""];
var comparisonsTitle = ['true', 'false', '1', '0', '-1', '"1"', '"0"', '"-1"', 'null', 'undefined', '[]', '{}', '""'];
var len = comparisons.length;
var html = '', bool;
for (var y = -1; y < len; y++) {
html += "<tr>";
for (var x = 0; x < len; x++) {
if (y == -1) {
if (x == 0) { html += '<th></th>'; }
html += '<th>' + comparisonsTitle[x] + '</th>';
} else {
if (x == 0) { html += '<th>' + comparisonsTitle[y] + '</th>'; }
bool = comparisons[x] == comparisons[y];
html += '<td class="' + bool + '">' + bool + '</td>';
}
}
html += '</tr>';
}
document.getElementsByTagName('table')[0].innerHTML = html;
</script>
</body>
</html>
@albohlabs
Copy link

Nice one.

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