Possible Duplicate:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
How is a condition inside the if
statement evaluated to true
or false
in JavaScript?
Possible Duplicate:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
How is a condition inside the if
statement evaluated to true
or false
in JavaScript?
undefined
, null
, ""
, 0
, NaN
, and false
are all "falsey" values. Everything else is a "truthy" value.
If you test a "falsey" value, the condition is false. E.g.:
var a = 0;
if (a) {
// Doesn't happen
}
else {
// Does happen
}
If you test a "truthy" value, the condition is true:
var a = 1;
if (a) {
// Does happen
}
else {
// Doesn't happen
}
Whatever the result of the condition expression is, it is converted to a Boolean by ToBoolean
:
- Let
exprRef
be the result of evaluatingExpression
.- If
ToBoolean(GetValue(exprRef))
istrue
, then
Return the result of evaluating the firstStatement
.- Else,
Return the result of evaluating the secondStatement
.
For each data type or value, the conversion rules to a Boolean are clearly defined. So, for example, undefined
and null
are both converted to false
.