How to make the length of an Array read-only in JavaScript

Sometimes, you may come across a requirement that once the array is created, its length should not be changed. In this blog post, let us explore how you can achieve that.

Let us say you have an array as shown below,


let foo = ['1', '11'];
console.log(foo.length); // 2
console.log(foo[1]); //11

As you see, the length of the array is 2, and you can print the values of an array using the index.  By default, JavaScript allows you to change the length of the array. So, you can very much do as shown below,


foo.length = 50;
console.log(foo.length); // 50
console.log(foo[1]);//11
console.log(foo[36]);// undefined 

Now the length is changed to 50, and every item from index 2 to 49 is set to undefined. You can verify that using a for..of loop


for (let a of foo) {
    console.log(a);
}

You can empty an array by setting length property to zero.


foo.length = 0;
console.log(foo.length); // 0
console.log(foo[1]);  // undefined 

So, sometimes you may come across a requirement to make length property read-only. That means after the array is created and initialized, length property cannot be changed. 

You can achieve it by using Object Property Descriptor.  Keep in mind that,

  1. An array is an object.
  2. Length is a property on an array object.

By setting the writable property of length to false, you can make it as read-only.


let foo = ['1', '11'];
 
Object.defineProperty(foo, 'length', { writable: false });
 
foo.length = 100; // will be ignored 
foo[2] = 'dj';
console.log(foo[2]); // undefined
console.log(foo.length); // 2

In the above code snippet, changing the length value will be ignored by JavaScript. If you run the same code in the strict mode, you get the error as below.


'use strict'
 
let foo = ['1', '11'];
 
Object.defineProperty(foo, 'length', { writable: false });
 
foo.length = 100; // will be ignored 
foo[2] = 'dj';
console.log(foo[2]); // undefined
console.log(foo.length); // 2

You will get an error as below,

In this way, by using the object property descriptor, you can make an array’s length property read-only in JavaScript.

I hope you find this post useful. Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s