how to find length of array in javascript without using length method

hljs.highlightAll();

How to Find Length of Array in JavaScript Without Using Length Method

If you want to find the length of an array in JavaScript without using the length method, there are a few ways to do it:

1. Using a Loop

You can use a for loop to iterate through the array and count the number of elements:


    var arr = [1, 2, 3, 4, 5];
    var count = 0;

    for(var i in arr) {
      count++;
    }

    console.log(count); // output: 5
  

In this example, we declare a variable called count and then use a for loop to iterate over the array. For each element in the array, we increment the count variable by 1. Once the loop has finished executing, the count variable will contain the number of elements in the array.

2. Using the Spread Operator

You can also use the spread operator to convert the array into a list of arguments and then count the number of arguments:


    var arr = [1, 2, 3, 4, 5];
    var count = [...arr].length;

    console.log(count); // output: 5
  

In this example, we use the spread operator to convert the array into a list of arguments, and then use the length property to get the number of arguments. Since the spread operator creates a copy of the array, the original array remains unchanged.

3. Using the Reduce Method

You can also use the reduce method to iterate over the array and accumulate a count of the number of elements:


    var arr = [1, 2, 3, 4, 5];
    var count = arr.reduce(function(acc, val) {
      return acc + 1;
    }, 0);

    console.log(count); // output: 5
  

In this example, we use the reduce method to iterate over the array and accumulate a count of the number of elements. The initial value of the accumulator is set to 0, and for each element in the array, we add 1 to the accumulator. Once the reduce method has finished executing, the accumulator will contain the number of elements in the array.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe