Loose Comparison with == in JavaScript

by djesse

HTML

<!DOCTYPE html>
<html>
    <body>
        <h1>Loose comparison with == in JavaScript</h1>
        <table></table>
    </body>
</html>

CSS

body { font-family: Arial, sans-serif; }
th, td {
  text-align: center;
  padding: 10px;
}

th { background-color: #f0f0f0; }
.true  { background-color: #a0ffa0; }
.false { background-color: #ffa0e0; }

JavaScript

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;