JavaScript - Create an empty array of fixed length

By IncludeHelp Last updated : January 20, 2024

An empty array of fixed length is an array that does not have any element but has a fixed length.

Problem statement

The task is to create an empty array of fixed length in JavaScript.

Creating an empty array of fixed length

To create an empty array of fixed length, first create an empty array and then initialize it with a fixed length using the Array.length property. To create an empty array, just use the empty square brackets ([]) without any element.

JavaScript code to create an empty array of fixed length

The following example creates an empty array arr with a fixed length of 5.

// declaring an empty array
var arr = [];

// initializing a length to arr
arr.length = 3;

// printing the length and length
console.log("arr is: ", arr);
console.log("arr's length is: ", arr.length);

Output

The output of the above code is:

arr is: [empty × 3]
arr's length is:  3

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

All JavaScript Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.