Categories
JavaScript Answers

How to create a fixed length array in JavaScript?

Spread the love

Sometimes, we want to create a fixed length array in JavaScript.

In this article, we’ll look at how to create a fixed length array in JavaScript.

How to create a fixed length array in JavaScript?

To create a fixed length array in JavaScript, we use the Object.seal method.

For instance, we write

const a = new Array(100);
a.fill(1);
Object.seal(a);

to create array a with length 100.

Then we call fill to fill all the slots with 1’s.

Finally, we call Object.seal with a to stop its length from being changed.

Conclusion

To create a fixed length array in JavaScript, we use the Object.seal method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *