[SOLVED] Check if JavaScript array is empty with Examples

This tutorial simplifies a check if JavaScript array is empty or exists by explaining critical concepts like primitives vs references, Boolean logic, and falsiness vs truthiness. It then walks you through practical examples to check if an array is empty or exists.

Let's get started.

Advertisement

 

Understand the key concepts to ease the check if JavaScript array is empty or exists

Primitives vs Objects

At a high level, we can classify JavaScript data types into primitives and references.

Primitives are the simplest, immutable data types like numbers, strings, and booleans. On the other hand, references pack multiple primitives.

For example, an array, a function, or an object could house a string, boolean, or number.

// An array
const array = [59, "FivetyNine", true]

// An object
const object = { age: 59, quote: "FivetyNine", lovesTenis: true }

At an intermediate level, all primitives are objects because they store key-value pairs.

For example, an array stores values referenced by indices (keys). As a result, we can conclude that an array is a special type of object that organizes primitives with indices.

More excitingly, the typeof operator recognizes an array as an object.

Advertisement
const a = 3
const b = 'S'
const c = true
const d = {a: 3, b: 'S', c: true}
const e = [a, b, c, d]

console.log(typeof a) // number
console.log(typeof b) // string
console.log(typeof c) // boolean
console.log(typeof d) // object
console.log(typeof e) // object

On a lower level, everything in JavaScript is an object; your custom variables get piped into an object: an instance of a class or constructor function.

For instance, a string is a descendant object of the String() constructor function. Likewise, true is an object linked to the Boolean() constructor.

Knowing how effectively apply the Boolean() constructor is a massive step toward a check if JavaScript array is empty or exists.

 

The Boolean Logic

The Boolean logic states that something either exists or not. Existence is represented by true, while nonexistence is denoted by false. Therefore, we can store a variable as either true or false.

const c = true // equates to true
const isGreaterThan = 5 < 2 // equates to false

We can explicitly or implicitly check a condition in a control flow.

// explicit comparison
if (isGreaterThan === true) console.log("Yes") // Yes

// implicit comparison
if (isGreaterThan) console.log("Yes") // Yes

Boolean logic extends into falsy and truthy values.

Advertisement

 

Falsy vs Truthy values

A falsy value is associated with emptiness or false in the Boolean logic.

null, undefined, NaN, false, zero (, -0, or 0n), an empty string ("") or an empty array ([]) expresses emptiness.

We can confirm an expression's emptiness by piping its value into the Boolean() constructor.

const a = null
const b = undefined
const c = 0
const d = -0
const e = ""
const f = []
const g = NaN
const h = 0n

const isFalsy0 = Boolean(h) // false
const isFalsy1 = Boolean(h) // false
const isFalsy2 = Boolean(h) // false
const isFalsy3 = Boolean(h) // false
const isFalsy4 = Boolean(h) // false
const isFalsy5 = Boolean(h) // false
const isFalsy6 = Boolean(h) // false
const isFalsy7 = Boolean(h) // false
const isFalsy8 = Boolean(h) // false

Any value that is not falsy is truthy. For example, an array with elements is truthy.

const thisArray = [19, 29, 59, 79, 89]
const isNotEmpty = Boolean(thisArray)

console.log(isNotEmpty) // true

Now that you understand the concepts to verify the emptiness and existence of an array, let's see how to check if JavaScript array is empty or exists.

 

Setup Lab Environment

Launch the terminal and create the project directory with four .js files.

Advertisement
mkdir project_directory && cd project_directory
touch example1.js example2.js example3.js example4.js

We will the files as follows;

example1.js: Check if an array exists

example2.js: Check whether the given variable is an array

example3.js: Check if an array is empty

example4.js: check if JavaScript array is empty or exists using one expression

In the following section, you can open each of the files using a preferred code editor like Visual Studio Code.

Advertisement

[SOLVED] Check if JavaScript array is empty with Examples

 

Practical examples of check if JavaScript array is empty or exists

Example~1: Check if an JS array exists

It would be best to check if the target array exists before verifying if it is empty. We can check the existence of an array by comparing it to booleans.

Input

const array = []
const arrayExists = array ? true : false
console.log(arrayExists)

Using the ternary operator, we check the existence of the array variable. We then store the result in the arrayExists variable before logging it on the console.

Output

true

[SOLVED] Check if JavaScript array is empty with Examples

It is true true we have defined the array variable. So, the array array exists.

 

Example~2: Check whether the given variable is an array

Apart from knowing whether the array whose emptiness we want to check exists, we may want to know if the given variable is exactly an array, not another type of object.

Advertisement

We can use the isArray() method of the Array() constructor function's instance.

Input

const areYouAnArray = []
const areYouAnArray1 = {}

const existsAndOfArrayDataStructureType = Array.isArray(areYouAnArray)
const existsAndOfArrayDataStructureType1 = Array.isArray(areYouAnArray1)

console.log(existsAndOfArrayDataStructureType, existsAndOfArrayDataStructureType1)

Output

true false

[SOLVED] Check if JavaScript array is empty with Examples

Although both areYouAnArray and areYouAnArray1 are objects, areYouAnArray is an array, whereas areYouAnArray1 is not.

 

Example~3: Check if an JS array is empty

The length property plays a massive role in checking if an array is empty.

Input

Advertisement
const array = []

const isNotEmpty = array.length ? true : false
console.log(isNotEmpty)

const isNotEmpty1 = array.length > 0 ? true : false
console.log(isNotEmpty1)

const isNotEmpty2 = Boolean(array?.length);
console.log(isNotEmpty2)

isNotEmpty, isNotEmpty1, and isNotEmpty2 check the falsiness in the respective array.length's expression.

Output

false
false
false

[SOLVED] Check if JavaScript array is empty with Examples

array.length equals zero (), which is a falsy value. array.length > 0 is an explicit comparison checking whether the array.length () is greater than zero (). Definitely, that is false false!

Lastly, we check the truthiness or falsiness of the outcome of the optional chaining (array?.length) piped into the Boolean() constructor, which is zero (). And zero () is a falsy value.

 

Example~4: Check if JavaScript array is empty or not using one expression

Instead of separately checking whether an array exists or is empty, we can combine the two checks into a giant expression.

The check is possible via comparison operators like || (or) and && (and). Here, we use the left-hand side of the equation to check for existence, while the right-hand side checks whether the array is empty.

Besides, we can use the optional chaining ?. operator.

Input

const array = []

const existsAndNotEmpty = array && array.length > 0 ? true : false
console.log(existsAndNotEmpty)

const existsAndNotEmpty1 = array === undefined && array.length === 0 ? true : false
console.log(existsAndNotEmpty1)

const existsAndNotEmpty2 = array?.length ? true : false
console.log(existsAndNotEmpty2)

Output

false
false
false

Hint: Negative has higher precedence than positive.

In existsAndNotEmpty, the array exists BUT its length (array.length) is not greater than zero ().

In existsAndNotEmpty1, the array exists, so the array === undefined expression is NOT true false. However, it is true true that the array's length equates to zero (array.length === 0).

In existsAndNotEmpty2, the output of array?.length is falsy.

check if JavaScript array is empty or exists

 

Conclusion

The first step toward check if JavaScript array is empty or exists is understanding the roots of arrays. You should then comprehend the Boolean logic and falsiness.

Lastly, as shown in this tutorial, you can separately check for an array's existence and emptiness or create one expression accommodating both checks.

 

Related Keywords: javascript array is empty, array isempty javascript, array isempty js, js array isempty, js check if array is empty, javascript check if array is empty, check if array is empty javascript

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X