JavaScript Array.length Property

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript array.length:
  2. Example Code: Use array.length to Get the Total Number of Items in the Given Array
  3. Example Code: Use array.length to Set the Total Number of Items in an Array
JavaScript Array.length Property

In JavaScript, the array.length property finds the total number of items an array contains. This method can also be used to set the new length of the array without adding or removing the items.

Syntax of JavaScript array.length:

refarray.length;
refarray.length = number;

Parameter

It does not take any parameters.

Return

This method returns the number of items added to the given array.

Example Code: Use array.length to Get the Total Number of Items in the Given Array

In JavaScript, we can use the array.length property to find the total number of items added to a given array. The output can change depending on the number of items added or removed using different methods in JavaScript.

In this example, we used the array.length method to get the total number of items in the given array.

let array = ["1","2","3","4"];
array[4,5,6] = ["5","6","7"];
console.log(array.length);

Output:

7

Example Code: Use array.length to Set the Total Number of Items in an Array

Users can set a particular number of items in an array using the array.length method. If the number is less than the items added to the array previously, then extra items won’t be displayed or counted in the given array.

In the example below, we have created an array with three items and used array.length to set the total items into the array.

const array = ["javascript", "java", "web"];
array.length = 5;
console.log(array);
array.length = 2;
console.log(array);

Output:

[ 'javascript', 'java', 'web', <2 empty items> ]
[ 'javascript', 'java' ]

The array.length property determines and returns the number of items in a given array. We can also set the number of items displayed from the index position using the array.length method.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Array