Home »
JavaScript »
JavaScript Examples
JavaScript - Array with non-writable length
By IncludeHelp Last updated : January 20, 2024
In JavaScript, an array has its length and when any element is added or moved to/from an array, its length is increased or decreased automatically. In this tutorial, you will learn how can you make it a non-writable length.
Problem statement
The task is to define (create) an array with non-writable length.
Array with non-writable length
To define an array with non-writable length, set the .length property to non-writable mode by assigning false to writable attribute using the Object.DefineProperty() method. After that, the array will not be able to update it. Also, use the "strict mode".
Consider the below code statement:
Object.defineProperty(array_name, "length", { writable: false });
JavaScript code to create an array with non-writable length
The following example creates an array arr with non-writable length.
"use strict";
// declaring an array
const arr = [10, 20, 30, 40, 50];
// Before making it non-writable length
// adding element
arr.push(60); // No error
// printing array
console.log("arr is:", arr);
// Making non-writable length
Object.defineProperty(arr, "length", {
writable: false
});
// Before making it non-writable length
// adding element
arr.push(6); // return TypeError
Output
The output of the above code is:
arr is: [10, 20, 30, 40, 50, 60]
Uncaught TypeError: Cannot assign to read only property 'length' of object '[object Array]'
at Array.push (<anonymous>)
at <anonymous>:20:5
If you try to add an element after making a non-writable length, it will the following TypeError:
TypeError: Cannot assign to read only property 'length' of object '[object Array]'
To understand the above example, you should have the basic knowledge of the following JavaScript topics: