How to get the size of an array in JavaScript ?

Getting the size of an array in JavaScript involves determining the number of elements it holds. This operation is essential for understanding and managing array data. JavaScript provides various methods and properties, such as length, reduce(), and others, to accomplish this task efficiently.

Here are some common approaches:

Table of Content

  • JavaScript Array length Property:
  • Using reduce() method

JavaScript Array length Property

The JavaScript Array Length returns an unsigned integer value that represents the number of elements present in the array. The value is non-negative and always a 32-bit integer.

Example 1: In this example, we will store a string inside of an array and find out the length of that array.

Javascript
// Defining an String array
let arr1 = ["Eat", "Code", "sleep", "Repeat"];
// Storing length of arr1 in len1 variable
let len1 = arr1.length;

// Displaying the length of arr1
console.log("Length of the Array:" + len1);

Output
Length of the Array:4

Example 2: In this example we will store a number inside of an array and find out the length of that array.

Javascript
// Defining an number array
let arr2 = [100, 200, 300, 400, 500];
// Storing length of arr2 in len2 variable
let len2 = arr2.length;

// Displaying the length of arr2
console.log("Length of arr2:" + len2);

Output
Length of arr2:5

Using reduce() method

In JavaScript, the reduce() method iterates over each element of an array, accumulating a value based on a callback function. To get the size of an array, reduce() increments an accumulator for each element, returning the final count.

Example: In this example we use reduce() to count the elements in the array, starting from 0. It then logs the size of the array.

JavaScript
const array = [1, 2, 3, 4, 5];
const size = array.reduce((acc) => acc + 1, 0);
console.log(" the size of the given array is : "+size); 

Output
 the size of the given array is : 5