I understand that in terms of boolean
x = true;
if(x) //This is the same as if(x === True)
doSomething();
But if one were to set x to a number, then what does the if condition mean? Does the condition mean if(x === true)? If so, why is that?
I understand that in terms of boolean
x = true;
if(x) //This is the same as if(x === True)
doSomething();
But if one were to set x to a number, then what does the if condition mean? Does the condition mean if(x === true)? If so, why is that?
In javascript the below are falsey
false
undefined
null
0
""
NaN
Anything except the above are truthy, including numbers, except 0
. So 10
is a truthy value and hence the if
block, executes.
in short is as follows:
//!length = if(x.length);
var a; //undefined == if(!a) == !length
var b = ""; //void == if(!b)
var c = " "; //blank == if(c) == length
var d = "text"; //there == if(d) == length
var e = true; //true == true == if(e)
var f = false; //false == false == if(!f)
var g = null; //false == if(!g) == !length
var h = 0; //0 == if(!h)
var i = 1; //true == if(i)
var j = 0/0; //NaN == if(!j)
var k = document.body; // == if(k)
var l = document.getElementById("nothing"); // if(!l) == !length
Javascript is very flexible with regards to checking for "null
" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:
if(!blah){
Which will check for empty strings (""
), null
, undefined
, false
and the numbers 0
and NaN
var a; //undefined == if(!a) == !length
var b = ""; //void == if(!b)
var c = " "; //blank == if(c) == length
var d = "text"; //there == if(d) == length
var e = true; //true == true == if(e)
var f = false; //false == false == if(!f)
var g = null; //false == if(!g) == !length
var h = 0; //0 == if(!h)
var i = 1; //true == if(i)
var j = 0/0; //NaN == if(!j)
var k = document.body; // == if(k)
var l = document.getElementById("nothing"); // if(!l) == !length
consoletotal(l);
function consoletotal(bb){
consolea(bb);
consoleb(bb);
consolec(bb);
consoled(bb);
consolee(bb);
}
function consolea(bb){
if(bb){
console.log("yes" + bb);
}
}
function consoleb(bb){
if(bb===true){
console.log("true" + bb);
}
}
function consolec(bb){
if(bb===false){
console.log("false" + bb);
}
}
function consoled(bb){
if(!bb){
console.log("no" + bb);
}
}
function consolee(bb){
if(bb.length){
console.log("length" + bb);
}
}