JavaScript Array length

In this section, we will learn what the length property is and how to use it in JavaScript.

Array Size in JavaScript

In JavaScript, we can get the length or basically the number of elements in an array.

This is done with the help of `length` property.

This is a read/ write property and hence could be used to change the size of an array as well.

Example: length of an array in JavaScript

const arr = ["John","Doe","Jack","Omid","Ellen"];
console.log(`The number of elements is: ${arr.length}`);
for (let i = 0; i<arr.length; i++){
  console.log(arr[i]);
}

Output:

The number of elements is: 5

John

Doe

Jack

Omid

Ellen

Example: JavaScript get array length

const arr = ["John","Doe","Jack","Omid","Ellen"];

console.log(`The number of elements is: ${arr.length}`);

console.log(arr);

console.log("Now changing the size of the array");

arr.length = 3;

console.log(arr);

Output:

The number of elements is: 5
(5) ['John', 'Doe', 'Jack', 'Omid', 'Ellen']
Now changing the size of the array
(3) ['John', 'Doe', 'Jack']

As you can see, we’ve changed the size of the array to 3 and hence the size shrunk and two of the elements in this array are deleted so.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies