There are already many answers exist to check for undefined, null, empty or blank variable in JavaScript and jQuery still sometimes they mislead if not understood well. So this article is a straightforward manner to determine if a variable is undefined or has null/empty value or whatsoever.
Check undefined, null, empty or blank variable in JavaScript
While working with jQuery or JavaScript, if you don’t know whether a variable exists (that means, if it was declared) you should check with the typeof
operator. For instance
1 2 3 | if( typeof myVar !== 'undefined' ) { // myVar could get resolved and it's defined } |
If you are already sure or can make sure as shown in code above, that a variable is declared at least (no matter if it has a value or not), you should directly check if it has a truthy
value using the code written below:
1 2 3 | if( myVar ) { // myVar has truthy value } |
This will evaluate to true
if myVar's value
is not:
- null
- empty string (“”)
- undefined
- NaN
- false
- 0
The above list represents all possible falsy values in ECMA-/Javascript.
Also don’t try to assign a variable as parameter to a function with falsey
value else the JavaScript will throw only exception as code written below:
1 2 3 4 5 6 7 8 9 10 | var abc = document.getElementById('elem_exists'), xyz = document.getElementById('elem_not_exists'); function elemHandle(element) { // Some code to perform with element } elemHandle(abc); // works elemHandle(xyz); // ERROR! if(xyz) { elemHandle(xyz); } // works |
Hope it’s kinda clear and you can clearly and easily check & determine for undefined, null, empty or blank variable in JavaScript using the ways stated in the article.