![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Looping in JavaScript to count non-null and non-empty values
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
Advertisements