JavaScript array.length: Find the Length of an Array

The JavaScript length property is used to find the length of an array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      const cities = ["Tokyo", "Bangkok", "Dubai", "Berlin", "Frankfurt"];
      document.getElementById("xyz").innerHTML = cities.length;
   </script>
   
</body>
</html>
Output

This code produces an array of city names and assigns it to the cities constant variable.

const cities = ["Tokyo", "Bangkok", "Dubai", "Berlin", "Frankfurt"];

The names of five different cities are contained in the array's five elements.

The dot (.) notation is used to access the array's length property. The "length" property returns the number of array elements. Therefore, through the following JavaScript statement:

document.getElementById("xyz").innerHTML = cities.length;

The value of cities.length is set as the innerHTML property of an HTML element with ID "xyz". Therefore, when the code runs, the number 5 will be displayed inside the "p" tag with ID "xyz". This is because the "length" property returns the number of elements in the cities array, which is 5.

JavaScript length Syntax

The syntax of the length property in JavaScript is:

array.length

The array refers to the array whose length we need to find.

The length of an array represents the total number of items or elements available in the array.

Advantages of the array.length property in JavaScript

Disadvantages of the array.length property in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!