Computer >> Computer tutorials >  >> Programming >> Javascript

Is there any way to check if there is a null value in an object or array in JavaScript?


To check if there is a null value in an object or array, use the concept of includes().

Example

Following is the code −

var nameArray1 = ["John", "David", "Mike", "Sam", null];
if (nameArray1.includes(null) == true) {
   console.log("array1 contains null value");
} else {
   console.log("array1 does not contains null value");
}
var nameArray2 = ["Adam", "Bob", "Robert"];
if (nameArray2.includes(null) == true) {
   console.log("array2 contains null value");
} else {
   console.log("array2 does not contains null value");
}
var objectData = { name: null };
if (Object.values(objectData).includes(null)) {
   console.log("object contains null value");
   } else {
      console.log("object does not contains null value");
}

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

node fileName.js.

Here, my file name is demo314.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo314.js
array1 contains null value
array2 does not contains null value
object contains null value