Truthy- and Falsy- ness
by Ari Zelanko
HTML
<p>Truthy- or Falsy- ness:</p>
<div class="testouter">
</div><br/>
<p>"||" and "&&"</p>
<div class="testouter">
</div><br/>
CSS
.testouter {
border: solid thin;
}
JavaScript
(function() { // Test Truthy and Falsy
//debugger;
var resultcontainer = $(".testouter")[0],
test = function(value) {
var typeOf = typeof value,
isString = typeOf === "string",
valueLabel, resultHTML;
valueLabel = (isString ? "\"" + value + "\"" : (value + "(") + typeOf + ")") + ": ";
resultHTML = valueLabel + ( !! value) + "<br/>";
resultcontainer.innerHTML += resultHTML;
},
testSuite = [
undefined,
null,
NaN,
true,
"true",
false,
"false",
"",
" ",
"_",
"a",
"0",
0,
1,
"1",
{},
[]
],
run = function() {
var testValueCount = testSuite.length,
i;
for (i = 0; i < testValueCount; i++) {
test(testSuite[i]);
}
};
run();
}());
(function() { // Test || and && operators
debugger;
var resultcontainer = $(".testouter")[1],
test = function(testExpression) {
var label = "eval(\"" + testExpression + "\"): ",
resultHTML = eval(testExpression);
resultcontainer.innerHTML += label + resultHTML + "<br/>";
},
testSuite = [
("true || false"),
("false || true"),
("true || 1"),
("false || 1"),
("0 || 1"),
("1 || 0"),
("true && false"),
("false && true"),
("true && 1"),
("false && 1"),
("0 && 1"),
("1 && 0")
],
run = function() {
var testValueCount = testSuite.length,
i;
for (i = 0; i < testValueCount; i++) {
test(testSuite[i]);
}
};
run();
}());