By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Get Count of JavaScript Array Elements

How you can count elements inside an array in JavaScript, and how to alert them back.

Edited: 2012-12-30 08:20

To get to know how many elements are in a JavaScript array, you can use array length property – the length property reflects the number of elements in an array. Saving the length of an array can be useful before iterating over the array – aka looping through the array. The below example will return the number of elements:

var aNArr = new Array();
aOurArray[0] = 'One';
aOurArray[1] = 'Two';
aOurArray[2] = 'Three';
aOurArray[3] = 'Four';

var length = aOurArray.length;

alert(length); // Returns 4

Keep in mind that Arrays in JavaScript are objects, and length is a property of the array object. We are simply accessing the property by typing:


Other properties and methods can be accessed in a similar way.

Looping through the array

The fastest way to iterate over the array, might be to first save the number of elements into a variable, and then use this in a while loop.

var aNArr = new Array();
aNArr[0] = 'One';
aNArr[1] = 'Two';
aNArr[2] = 'Three';
aNArr[3] = 'Four';

var length = aNArr.length;

var Counter = 0; // The counter variable
while(Counter < length){
	document.write(Counter + ":" + aNArr[Counter]);
	Counter++; // Increments the counter variable

The code between the curly { ... } brackets is executed each time the loop runs. The loop count variable is named counter for simplicity. The counter is simply getting incremented by one each time the loop runs.

See also

  1. How to use forEach
  2. While and For Loops