• JavaScript Video Tutorials

JavaScript - Array length Property



The JavaScript Array.length property is used to return the number of elements present in an array. For instance, if the array contains four elements, then the length property will return 4. The return value of the length property is always a non-negative integer which is less than 232.

Following are some scenarios where we can use the Array.length property −

  • To check the number of elements present in an array.
  • To check if an array is empty or not.
  • We can use this property to remove elements from the end of an array.
  • We can resize an array by setting a new length.

Syntax

Following is the syntax of JavaScript Array length property to return the length of an array −

array.length

Following is the syntax to set or return the number of elements in an array −

array.length = number

Return value

The length property of an array in JavaScript returns the number of elements in the array.

Examples

Example 1

In the following example, we are using the JavaScript Array.length property to calculate the length of the specified array.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
      let result = animals.length;
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

5

Example 2

Here, we are returning 3 elements from the provided array using the length property −

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
      animals.length = 3;
      document.getElementById("demo").innerHTML = animals;
   </script>
</body>
</html>

Output

Lion,Cheetah,Tiger

Example 3

If the provided array has no elements in it (empty array), the length property will return 0 as output.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = []
      let result = animals.length;
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

0

Example 4

When the "length" is set to bigger value than the orginal length, the array will be extended by adding empty slots −

<!DOCTYPE html>
<html>
<body>
   <script>
      const arr = [10, 20, 30];
      document.write(arr, "<br>");
      arr.length = 5;
      document.write(arr);
   </script>
</body>
</html>

Output

10,20,30
10,20,30,,
Advertisements