The simplest way to check if all values in array are null is to use the array every()
method. The every()
method loops through the array and compares each element to null
. If all array elements are null, then the every() method will return true
; otherwise, it will return false
.
let arr1 = [null, null]; let arr2 = [null, null, 21, undefined, true]; let result; result = arr1.every(element => element === null); console.log(result); //true result = arr2.every(element => element === null); console.log(result); //false
The explanation of the code is as follows:
The every()
method calls a callback function for each element of the array. Inside the callback function, the condition (element === null
) is specified. If any one of the elements does not satisfy the condition, then the every() method short-circuits and returns false
.
An alternative way to check if all values in array are null is to use the for...of loop. Inside the for...of loop, you compare each array element to null
. If the array element is not equal to null
, you set false
to the result
variable and break out the for...of loop.
let arr1 = [null, null]; let arr2 = [null, null, 21, undefined, true]; let result = true; for(let element of arr1){ if(element !== null){ result = false; break; } } console.log(result); //true result = true; for(let element of arr2){ if(element !== null){ result = false; break; } } console.log(result); //false