Length of Array in JavaScript

Length of Array in JavaScript | The length data property of an Array instance represents the number of elements in an array. The value is a 32-bit unsigned integer that is always numerically higher than the array’s highest index. An integer that is not negative and has a value lower than 2^32 is the value of the length attribute.

Syntax to access the length of an array in JavaScript:- arrayVariable.length

Example of how to check the length of an array in JavaScript:-

const numbers = [1, 2, 3];
const array = new Array(6);

console.log(numbers.length);
console.log(array.length);

Output:-

3
6

The array object observes the length property, which automatically synchronizes the length value and array content. This implies:

The array is truncated if the length is set to a value less than the current length; any more elements are removed. The array is extended if any index (a non-negative integer less than 2^32) is set above the current length; the length property is updated to reflect the new highest index.

In JavaScript, we can modify the length of an array after declaration using the length attribute. Example of modifying the length of an array:-

const numbers = [1, 2, 3];
const array = new Array(6);

console.log(numbers.length);
console.log(array.length);

// modifying length
numbers.length = 10;
array.length = 20;

console.log("New Lengths: ");
console.log(numbers.length);
console.log(array.length);

Output:-

3
6
New Lengths:
10
20

The assigned length value of an array must be positive and within the integer value range i.e. (2^32 – 1). If we try to assign a negative value or value greater than the integer range then we will get an error.

const numbers = [1, 2, 3];
numbers.length = 2 ** 32; // 4294967296
// RangeError: Invalid array length

Output:-

RangeError: Invalid array length

// Negative numbers are not allowed
const listC = new Array(-100); 
// RangeError: Invalid array length

Output:-

RangeError: Invalid array length

RangeError exception is thrown when the length is set to an invalid value, such as a negative number or a non-integer.

When the length is increased beyond the array’s existing length, empty slots rather than actual undefined values are added. See array methods and empty slots for more information on the unique interactions that empty slots have with them.

Leave a Comment

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