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 elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0
elements inside of it.
Let’s run through some examples.
Const myArray = [‘Horses’, ‘Dogs’, ‘Cats’];
Here we create a variable pointing towards an empty array.
Using the length property, we can check the length of the array:
myArray.length
This will return 3, because there are 3 items in the array.
To check if the array is empty or not with .length, we can do this in in three ways.
First, let’s create a new array with no elements.
const arr = []
Now we can check if the array is empty by using .length
.
arr.length
This will return 0, as there are 0 items in the array.
We can also explicitly check if the array is empty or not.
if (arr.length === 0) { console.log("Array is empty!") }
If our array is empty, the above message will get logged. If the array has elements in it, the code within the if
block will not run.
Here’s the third way to check whether or not an array is empty using .length.
#javascript #programming #developer #web-development