Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check for 'undefined' or 'null' in a JavaScript array and display only non-null values?
In JavaScript, arrays can contain null or undefined values. To display only non-null and non-undefined values, you need to check each element before processing it.
Sample Array with Mixed Values
Let's start with an array containing valid strings, null, and undefined values:
var firstName = ["John", null, "Mike", "David", "Bob", undefined];
console.log("Original array:", firstName);
Original array: [ 'John', null, 'Mike', 'David', 'Bob', undefined ]
Method 1: Using for Loop with != undefined
This approach checks if each element is not undefined. Since null != undefined evaluates to true, this will include null values:
var firstName = ["John", null, "Mike", "David", "Bob", undefined];
console.log("Method 1 - Checking != undefined:");
for (var index = 0; index < firstName.length; index++) {
if (firstName[index] != undefined) {
console.log(firstName[index]);
}
}
Method 1 - Checking != undefined: John null Mike David Bob
Method 2: Strict Check for Both null and undefined
To exclude both null and undefined values, check explicitly for both:
var firstName = ["John", null, "Mike", "David", "Bob", undefined];
console.log("Method 2 - Excluding both null and undefined:");
for (var index = 0; index < firstName.length; index++) {
if (firstName[index] !== null && firstName[index] !== undefined) {
console.log(firstName[index]);
}
}
Method 2 - Excluding both null and undefined: John Mike David Bob
Method 3: Using filter() Method
The filter() method provides a more functional approach:
var firstName = ["John", null, "Mike", "David", "Bob", undefined];
console.log("Method 3 - Using filter():");
var validNames = firstName.filter(function(name) {
return name !== null && name !== undefined;
});
validNames.forEach(function(name) {
console.log(name);
});
Method 3 - Using filter(): John Mike David Bob
Method 4: Using Truthy Check
For a more concise approach, you can use truthy evaluation (excludes null, undefined, empty strings, and 0):
var firstName = ["John", null, "Mike", "", "David", "Bob", undefined, 0];
console.log("Method 4 - Truthy check:");
for (var index = 0; index < firstName.length; index++) {
if (firstName[index]) {
console.log(firstName[index]);
}
}
Method 4 - Truthy check: John Mike David Bob
Comparison of Methods
| Method | Excludes null? | Excludes undefined? | Excludes empty strings? |
|---|---|---|---|
!= undefined |
No | Yes | No |
| Explicit check | Yes | Yes | No |
| Truthy check | Yes | Yes | Yes |
Conclusion
Use explicit checks (!== null && !== undefined) when you need precise control over which values to exclude. For broader filtering, truthy evaluation provides a concise solution that handles multiple falsy values.
