Given that there are only 2 potential values for each item in the 2D array, you will avoid allocating extra memory if you actually don't initialize the whole 2D array since JS arrays are essentially hashes (good explanation here: https://stackoverflow.com/a/20323491/2611078).

Initialize array:

var arr = [];

Then, when updating an item after user action:

 if (!arr[i]) { 
     arr[i] = [];
 }
 arr[i][j] = true;

Then, when checking the array:

if (arr[i] && arr[i][j]) {
    console.log('value');
} else {
    console.log('other (default) value');
}
Answer from Julie on Stack Overflow
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ check-if-javascript-array-is-empty-or-not-with-length
How to Check if a JavaScript Array is Empty or Not with .length
October 5, 2020 - By Madison Kanna When you're programming in JavaScript, you might need to know how to check whether an array is empty or not. To check if an array is empty or not, you can use the .length property. The length property sets or returns the number of el...
๐ŸŒ
Ash Allen Design
ashallendesign.co.uk โ€บ blog โ€บ how-to-check-if-an-array-is-empty-in-javascript
How to Check If an Array Is Empty in JavaScript
January 8, 2024 - If the array is empty, the expression will return true like so: ... There are some caveats to using this approach, and we'll cover them further down in this article. A similar approach to the previous one is to use the length property with the ! operator. The ! operator is the logical NOT operator, and since in JavaScript 0 is a falsy value, we can use the !
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ is-there-any-way-to-check-if-there-is-a-null-value-in-an-object-or-array-in-javascript
Is there any way to check if there is a null value in an object or array in JavaScript?
This is due to the fact that a declared variable that has not yet been given a value is undefined rather than null. There are many ways to check whether a value is null or not in JavaScript. Let's discuss few ways one by one. The Object.keys() is a method in JavaScript that returns an array of the keys of an object.
๐ŸŒ
SheCodes
shecodes.io โ€บ athena โ€บ 6421-how-to-check-array-for-null-values-in-javascript
[JavaScript] - How to Check Array for Null Values in | SheCodes
Learn how to use the Array.prototype.filter() method to check if an array has any null values, and use filters to exclude them from the output.
๐ŸŒ
DEV Community
dev.to โ€บ gaelgthomas โ€บ remove-null-values-from-array-in-javascript-4g5a
Remove Null Values From Array in JavaScript - DEV Community
September 24, 2022 - By using the filter method, we specify that we want to keep only elements that are different than null (yes, because life is beautiful!). If you print the new thisIsLife array, you'll have an array with non-null values.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Operators โ€บ null
null - JavaScript | MDN
Unlike undefined, JSON.stringify() can represent null faithfully. JavaScript is unique to have two nullish values: null and undefined. Semantically, their difference is very minor: undefined represents the absence of a value, while null represents the absence of an object.
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @gaelgthomas โ€บ remove-null-values-from-array-in-javascript-988298b01e3b
Remove Null Values From Array in JavaScript | by Gaรซl Thomas | Medium
September 24, 2022 - By using the filter method, we specify that we want to keep only elements that are different than null (yes, because life is beautiful!). If you print the new thisIsLife array, you'll have an array with non-null values.
๐ŸŒ
Code with Hugo
codewithhugo.com โ€บ avoiding-falsy-values-in-javascript-arrays
Avoid null/undefined in JavaScript arrays ยท Code with Hugo
December 13, 2018 - const noFalsyEvenZero = [NaN, undefined, null, 0, 1, 2, 2000, Infinity].filter( Boolean ); // [ 1, 2, 2000, Infinity ] const noFalsyExceptZero = [ NaN, undefined, null, 0, 1, 2, 2000, Infinity ].filter(el => el === 0 || Boolean(el)); // [ 0, 1, 2, 2000, Infinity ] Usually this happens when you want to compute something over an Array of objects where some of the elements have a property but others donโ€™t.
Top answer
1 of 1
1552

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array does not exist or is empty
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // โ‡’ do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // โ‡’ do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // โ‡’ probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // โ‡’ do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // โ‡’ probably OK to process array
}
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ javascript-convert-array-with-null-value-to-string
JavaScript - convert array with null value to string
If the value is falsy (null, undefined, or ""), it is replaced with an empty string "". Valid values are concatenated to form the final string. Below is an example of converting an array with a null value to a string using the reduce() method ?
๐ŸŒ
Webdevolution
webdevolution.com โ€บ blog โ€บ remove-null-values-from-array-javascript
Remove Null Values from Array in Javascript
const array = [1, 2, 3, null, " ", , undefined, 4, "Text", 0, false, true]; const removeEmptyValues = array => { const filtered = array.filter(e => e); return filtered; }; // returns [ 1 , 2 , 3 , 4 , 'Text' , true ] Another really simple way to remove all empty values from a javascript array is to combine the filter method with a boolean check expression.
๐ŸŒ
Mastering JS
masteringjs.io โ€บ tutorials โ€บ lodash โ€บ remove-null-from-array
Remove null from an Array with Lodash - Mastering JS
To remove null using filter, you can use the _.isNull function as the predicate. Simply add a negate in front of the isNull and all null values will be filtered out. const _ = require('lodash'); const array = ['a', true, null, undefined, 42]; // ['a', true, undefined, 42] _.filter(array, el => !_.isNull(el));
Top answer
1 of 1
3

When == is used to compare things of different types, like an array ([null]) and false, it has specific steps it goes through, called the Abstract Equality Algorithm (quoted below) to try to coerce them to things that it can compare. (Because == is the "loose" equality operator.)

First it sees if either operand is null or undefined, but in this case neither is.

Then it sees if it's comparing a number and a string, but that's not true in this case either.

Then it seems if either operand is a boolean, which of course on of these is. Since one of them is a boolean, it does an abstract operation called ToNumber in the spec to convert the other one to a number and does another ==. (The Number function, when used as a function and not a constructor, is basically a wrapper for that abstract ToNumber operation.)

So

[null] == false

becomes

0 == false

...because ToNumber([null]) coerces its argument to a string (via ToPrimitive), getting "", and then converts that to 0.

So now == has something where one of the operands is a number. SO it converts the other one to a number as well. Number(false) is 0.

Thus, [null] == false is true.


So what about [null, null] == false? When converting [null, null] to a string, we get ",", which ToNumber can't turn into a valid number. So it converts it to NaN. One of the fun things about NaN is that it's a number, but it's never equal to anything else. So:

[null, null] == false 

becomes

NaN == false

becomes

NaN == 0

...which is false, because (again) NaN is never equal to anything.


Here's that Abstract Equality Algorithm:

  1. ReturnIfAbrupt(x).
  2. ReturnIfAbrupt(y).
  3. If Type(x) is the same as Type(y), then

    a) Return the result of performing Strict Equality Comparison x === y.

  4. If x is null and y is undefined, return true.

  5. If x is undefined and y is null, return true.
  6. If Type(x) is Number and Type(y) is String,
    return the result of the comparison x == ToNumber(y).
  7. If Type(x) is String and Type(y) is Number,
    return the result of the comparison ToNumber(x) == y.
  8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
    return the result of the comparison x == ToPrimitive(y).
  11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
    return the result of the comparison ToPrimitive(x) == y.
  12. Return false.
๐ŸŒ
Flexiple
flexiple.com โ€บ javascript โ€บ check-if-array-empty-javascript
How to check if an array is empty using Javascript? - Flexiple
The Array.isArray() method is a sure shot method to check if a variable is an array or not and it automatically eliminates the cases of null and undefined without writing an additional script to check for it.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ check-if-an-array-is-empty-or-not-in-javascript
Check if an array is empty or not in JavaScript | GeeksforGeeks
November 9, 2024 - These are the following ways to remove the last Item from the given array: 1. Using pop() Method (Simple and Easiest Method for Any Array) The pop() method is used to get the last element of the given array it can also be used to remove the ...
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ how to check for null, undefined, or empty values in javascript
How to check for null, undefined, or empty values in JavaScript - LogRocket Blog
February 14, 2025 - Even if you were to do things in ... whereas JavaScript would simply return undefined. ... Weโ€™ve got an empty array, and then we try to print out the fifth element from the array. This is out of bounds. The result of this code is undefined. Basically, there are three conditions that we want to account for when checking for values that we think could be null or ...