Since an array never equals 0
when you use strict equality (===
), the 1st condition array === 0
fails. Since the array is not empty, the check array1.length <= 0
(btw - an array's length can never be less than 0) fails as well, and the result is false
.
Check if array in the 1st index (0
) is equal to 0:
const arr1 = [0];
const arr2 = [];
const arr3 = [5];
const isZeroArray = (arr) => arr.length === 0 || arr[0] === 0;
console.log(isZeroArray(arr1)); // true
console.log(isZeroArray(arr2)); // true
console.log(isZeroArray(arr3)); // false
In addition, if you want to check if all items in the array are 0
, you can use Array.every()
:
const arr1 = [0, 0, 0, 0];
const arr2 = [];
const arr3 = [5];
const isZeroArray = (arr) => arr.length === 0 || arr.every(e => e === 0);
console.log(isZeroArray(arr1)); // true
console.log(isZeroArray(arr2)); // true
console.log(isZeroArray(arr3)); // false