How to check for 'undefined' or 'null' in a JavaScript array and display only non-null values?


Let’s say the following is our array with non-null, null and undefined values −

var firstName=["John",null,"Mike","David","Bob",undefined];

You can check for undefined or null cases by using the following code −

Example

var firstName=["John",null,"Mike","David","Bob",undefined];
for(var index=0;index<firstName.length;index++){
   if(firstName[index]!=undefined)
      console.log(firstName[index]);
}

To run the above program, you need to use the following command −

node fileName.js.

Here my file name is demo203.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo203.js
John
Mike
David
Bob

Updated on: 14-Sep-2020

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements