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

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 14-Sep-2020 09:08:13
Advertisements