Categories
JavaScript Answers

How to create a fixed length array in JavaScript?

Spread the love

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

For instance, we write

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

to create array a with length 100.

Then we call fill with undefined to fill all empty slots with undefined.

We need to fill the empty slots since they can’t be changed after seal is called.

Then we call Object.seal to seal array a to keep its length from changing.

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 *