How to find length of an array in javascript

Learn how to find length of an array in javascript.

Many times we have need to get the size or length of the array but there is no good method for it in javascript.

We will see what are the drawbacks of the existing method and see how can we overcome them.

Javascript array’s are linear collection of data in which elements are accessed by an integer.

let arr = [1, 2, 3, 4, 5];
console.log(arr);

Output:
/*
Array(5)
 0: 1
 1: 2
 2: 3
 3: 4
 4: 5
 length: 5
__proto__: Array(0)
*/

It has an in-built method to get its size Array.length.

let arr = [1, 2, 3, 4, 5];
console.log(arr.length);

//5

This seems to be working fine but it does not, It has some bug. Actually the Array.length method does not return the count of elements present in the array instead in gives the largest index in the array + 1.

let arr = [];
arr[0] = 1;
arr[99] = 10;

console.log(arr.length);
//100

Even though we have only two elements in the array it returns 100 as the largest index is 99 and it has returned 99 + 1.

To solve this we can use Object.keys()

Using Object.Keys() to find an array length in javascript.

Object.Keys() method return’s an array with all the keys present in the object. As array is essentially an object in javascript. It returns its indexes as the keys.

let arr = [];
arr[0] = 1;
arr[99] = 10;

let indexes = Object.keys(arr);
console.log(indexes);
//["0", "99"]

Now we can get the length of this array of keys or indexes to find the length of the array.

let arr = [];
arr[0] = 1;
arr[99] = 10;

let indexes = Object.keys(arr);
console.log(indexes.length);
//2