How do you get the length for an array, and how can you create an empty array of fixed length?
In prior lecture videos you were first introduced to the length
property, this property returns the number of elements in an array. So here is a quick reminder on how it works:
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.length); // 3
It’s possible to have arrays with empty slots. Empty slots are defined as slots with nothing in them. This is different than an array with the value of undefined
. These types of arrays are known as sparse arrays. Here is an example:
const sparseArray = [1, , , 4];
console.log(sparseArray.length); // 4
In this case even though we only have two defined elements, 1
and 4
. The length is 4
because the highest index (3
) plus 1
gives us a length of 4
.
Now let’s discuss how to create an empty array of fixed length. There are few ways to do this in JavaScript but one common method is to use the Array()
constructor with a numeric argument. The Array()
constructor can be used with the new
keyword to create a new array. Here is an example:
const emptyArray = new Array(5);
console.log(emptyArray.length); // 5
console.log(emptyArray); // [,,,,]
In this example, we create a new array using the Array(5)
. This creates a sparse array with a length of 5
where all the slots are empty.
Another way to create an empty array of fixed length is to use the Array.from()
method with a length argument. This method creates an array of the specified length with all elements initialized to undefined
:
const fixedLengthArray = Array.from({ length: 5 });
console.log(fixedLengthArray.length); // 5
// [undefined, undefined, undefined, undefined, undefined]
console.log(fixedLengthArray);
If you want to create an array of specific length and fill it with a default value, you can use the Array.fill()
method:
const filledArray = new Array(3).fill(0);
console.log(filledArray); // [0, 0, 0]
This creates an array of length three and fills all elements with the value 0
.
Understanding how to get the length of an array and create arrays of fixed length is important for many programming tasks especially when you need to initialize arrays for specific algorithms or data structures.