You can just check if the variable has a truthy value or not. That means
if (value) {
// do something..
}
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.
You can just check if the variable has a truthy value or not. That means
if (value) {
// do something..
}
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.
This question has two interpretations:
Check if the variable has a value
Check if the variable has a truthy valueThe following answers both.
In JavaScript, a value could be nullish or not nullish, and a value could be falsy or truthy.
Nullish values are a proper subset of falsy values:
โญโ nullish โโโโโโโฎ โญโ not nullish โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โโโโโโโโโโโโโฌโโโโโโโฌโโโโโโโโฌโโโโฌโโโโโฌโโโโโโฌโโโโโโโฌโโโโฌโโโโโโโโโโฌโโโโโโ
โ undefined โ null โ false โ 0 โ "" โ ... โ true โ 1 โ "hello" โ ... โ
โโโโโโโโโโโโโดโโโโโโโดโโโโโโโโดโโโโดโโโโโดโโโโโโดโโโโโโโดโโโโดโโโโโโโโโโดโโโโโโ
โฐโ falsy โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โฐโ truthy โโโโโโโโโโโโโโโโฏ
Check if value is nullish (undefined or null)
Use one of the following depending on your coding style:
if (value == null) { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined) { /* value is nullish */ }
if ((value ?? null) === null) { /* value is nullish */ }
Notes:
- The
==operator works because it has a special case for null vs undefined comparison - The
===operator is more readable (opinion based), eqeqeq friendly and allows checking for undefined and null separately - The first and third examples work identically, however the third one is rarely seen in production code
- The fourth example uses nullish coalescing operator to change nullish values to
nullfor straight forward comparison
Check if value is not nullish
if (value != null) { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined) { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null) { /* value is not nullish, although it could be falsy */ }
Check if value is falsy
Use the ! operator:
if (!value) { /* value is falsy */ }
Check if value is truthy
if (value) { /* value is truthy */ }
Data validation
The nullish, falsy and truthy checks cannot be used for data validation on their own. For example, 0 (falsy) is valid age of a person and -1 (truthy) is not. Additional logic needs to be added on case-by-case basis. Some examples:
/*
* check if value is greater than/equal to 0
* note that we cannot use truthy check here because 0 must be allowed
*/
[null, -1, 0, 1].forEach(num => {
if (num != null && num >= 0) {
console.log("%o is not nullish and greater than/equal to 0", num);
} else {
console.log("%o is bad", num);
}
});
/*
* check if value is not empty-or-whitespace string
*/
[null, "", " ", "hello"].forEach(str => {
if (str && /\S/.test(str)) {
console.log("%o is truthy and has non-whitespace characters", str);
} else {
console.log("%o is bad", str);
}
});
/*
* check if value is not an empty array
* check for truthy before checking the length property
*/
[null, [], [1]].forEach(arr => {
if (arr && arr.length) {
console.log("%o is truthy and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});
/*
* check if value is not an empty array
* using optional chaining operator to make sure that the value is not nullish
*/
[null, [], [1]].forEach(arr => {
if (arr?.length) {
console.log("%o is not nullish and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});
I've seen so many methods; but I am looking for a simple style I can adopt in my code to keep it consistent:
if (PostCodeInformation !== null PostCodeInformation !== undefined){
}
Videos
There's no isEmpty() method, you have to check for the type and the length:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test is undefined or null.
Ignoring whitespace strings, you could use this to check for null, empty and undefined:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
It is concise and it works for undefined properties, although it's not the most readable.
If you're testing for an empty string:
if(myVar === ''){ // do stuff };
If you're checking for a variable that has been declared, but not defined:
if(myVar === null){ // do stuff };
If you're checking for a variable that may not be defined:
if(myVar === undefined){ // do stuff };
If you're checking both i.e, either variable is null or undefined:
if(myVar == null){ // do stuff };
This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.
// quick and dirty will be true for '', null, undefined, 0, NaN and false.
if (!x)
// test for null OR undefined
if (x == null)
// test for undefined OR null
if (x == undefined)
// test for undefined
if (x === undefined)
// or safer test for undefined since the variable undefined can be set causing tests against it to fail.
if (typeof x == 'undefined')
// test for empty string
if (x === '')
// if you know its an array
if (x.length == 0)
// or
if (!x.length)
// BONUS test for empty object
var empty = true, fld;
for (fld in x) {
empty = false;
break;
}