JavaScript: If you want to check whether a variable is defined, you can use typeof:
Example
if(typeof someVar == 'undefined') {
document.write("Variable someVar is not defined");
} else {
document.write("Variable someVar is defined");
}
document.write("Variable someVar is not defined");
} else {
document.write("Variable someVar is defined");
}
Try it »
JavaScript: If you only want to check whether a defined variable is true, you can directly use the following method:
Example
if (strValue) {
// Code executed when strValue is true
} else {
// Code executed when strValue is false
}
// Code executed when strValue is true
} else {
// Code executed when strValue is false
}
Try it »
The following uses a regular expression method to check whether a variable is defined and not empty; it is a relatively complete method:
Example
if ( // Return the determined value
(typeof x == 'undefined')
||
(x == null)
||
(x == false) // Similar to: !x
||
(x.length == 0)
||
(x == 0) // Here it checks 0; no need to deliberately remove it
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
) {
document.write("Variable is not defined or is empty");
}
(typeof x == 'undefined')
||
(x == null)
||
(x == false) // Similar to: !x
||
(x.length == 0)
||
(x == 0) // Here it checks 0; no need to deliberately remove it
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
) {
document.write("Variable is not defined or is empty");
}
Try it »
You can also encapsulate a method to check, covering null, 0, false, etc., suitable for defined variables:
Example
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
Try it »