Skip to content
the poor coder

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

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

    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:

Text

    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:

Text

    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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC