How to Create an Empty Array in JavaScript?
Learn how to create an empty array in JavaScript and what is the concept behind it.
There are two ways in Javascript you can create a new empty array.
- Simple declaration method
- Constructor method
Most people use the simple declaration method to construct a new array. It’s fast and efficient.
const myArray = [];
However, if you are coming from Java or you already have an array length in mind, you can Use the constructor method to create a new array.
const myArray = new Array(arrayLength);
How to Verify an Array?
If you want to verify if the array is created, you can use the .isArray()
method.
Array.isArray(myArray);
It it's a valid array, it should return true
, else it will return false
.
Can You Have an Empty Array?
Yes, you can have an empty array. If you want to check if the array is empty or not, you can use the .length
property.
If the array.length
returns 0, that means the array is empty.
What is The Difference Between a null Array and an Empty Array?
Technically there is nothing as a null array in javascript!
However, you can store a null value inside an array like this.
const newArray = [null]
You can check if the array is empty or not by the above-mentioned method.
In JavaScript, is an empty Array Return false
or true
?
// Straight Equality
[] == true; // false
[] == false; // true
// Conversion
Boolean([]); // true
! Boolean([]); // false
// Implied Conversion
! []; // false
!! []; // true
- If you check through straight equality, the empty array returns false.
- However, if you convert the empty array to a boolean assert, then the empty array returns true. It’s also the same for the forced conversion with the bang operator.
So, I recommend using .length to determine if an array is empty or not.
How to create an empty array of objects in javascript?
Creating an empty array of objects is a two-step process.
You have to use the array.push() method to add an item to the end of an empty array.
Step 1:
Create a new empty array.
const sampleArr = []
Step 2:
Push an empty object inside the array.
sampleArr.push(new Object())
If you want to add multiple empty objects inside an empty array, you can use a for-loop.
const n = 50;
For (i = 0; i < n; i++){
sampleArr.push(new Object())
}
That’s it for today.
If you need further help, you can connect with me on Twitter
Go to my Portfolio
Read my other blogs: