Looping in JavaScript to count non-null and non-empty values

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say the following are our values −

let subjectNames = ['JavaScript', 'Angular', 'AngularJS','Java'];

To count the non-empty and non-null values, use the forEach(). The syntax is as follows −

yourArrayName.forEach(anyVariableName =>{
   yourStatement1
   .
   .
   .
   N
   }
}
)

Now, use the if statement and check −

var count=0
subjectNames.forEach(subject =>{
   if(subject!=' ' || subject!=null){
      count+=1;
      }
   }
)

Example

let subjectNames = ['JavaScript', 'Angular', 'AngularJS','Java'];
var count=0
subjectNames.forEach(subject =>{
   if(subject!=' ' || subject!=null){
         count+=1;
      }
   }
)
console.log("Number of subject=="+count);

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

node fileName.js.

Here, my file name is demo47.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo47.js
Number of subject==4
raja
Published on 03-Sep-2020 06:03:21
Advertisements