JavaScript | string - boolean type conversion
by Zoltan Boros
HTML
<p>Empty string is converted to boolean false, however boolean false is converted to string "false".</p>
<pre id="out"></pre>
JavaScript
var out = document.getElementById("out");
function print(string)
{
out.innerHTML += string + "\n";
}
var x = "";
print("Value: [" + x + "] (" + typeof x + ")");
x = Boolean(x);
print("Value as boolean: [" + x + "] (" + typeof x + ")");
x = x.valueOf();
print("Its primitve value: [" + x + "] (" + typeof x + ")");
x = false;
print("Value: [" + x + "] (" + typeof x + ")");
x = x.toString();
print("Value as string: [" + x + "] (" + typeof x + ")");
x = false;
if (x == "") {
print('[' + x + '] (' + typeof x + ') equals to ""');
} else {
print('[' + x + '] (' + typeof x + ') does NOT equal to ""');
}
x = "";
if (x == false) {
print('[' + x + '] (' + typeof x + ') equals to false');
} else {
print('[' + x + '] (' + typeof x + ') does NOT equal to false');
}