11, Jan 2023
Array() constructor, or the array literal notation
Here are a few examples:
let myArray = new Array(5); // creates an array with length of 5 console.log(myArray.length); // prints 5
Using the array literal notation:
let myArray = new Array(5); console.log(myArray.length); // prints 5
Please note that both examples will create an array with a length of 5, but with no elements in it. You can also fill the array with values if you want, for example:
let myArray = new Array(5).fill(0); console.log(myArray); // prints [0,0,0,0,0]
It’s important to know that the length property of an array is a dynamic property, this means that if you add or remove elements from the array, the length will change accordingly.
let myArray = ; console.log(myArray.length); // prints 0 myArray.push(1); console.log(myArray.length); // prints 1
Another way to set a length of an array is by using the
.length property, and just set the number you want it to be.
let myArray = [1,2,3,4,5]; myArray.length = 2; console.log(myArray); // prints [1,2]
This truncates the array, keeping only the first two elements, and removing the rest.
It’s worth noting that when using
.length property, it can be set to a smaller number, that will truncate the array, or to a larger number, that will set undefined values to the added positions.
Initializing the array with a specific length can be useful when you know in advance the size of the data you’ll be working with, it will also allow to work with indexes more efficiently.