How to Get Array or String Length in JavaScript
To get the length of a string or array in JavaScript, use the built-in .length
property. To demonstrate this, let's look at a few examples.
Array Length
var fruit = ['Apple','Orange','Strawberry','Melon'];
console.log(fruit.length);
4
String Length
Here is another example with a string.
var fruit = 'Fruit';
console.log(fruit.length);
5
Here is another example demonstrating how to use .length
to loop through every array element:
var fruit = ['Apple','Orange','Strawberry','Melon'];
for (var i = 0; i < fruit.length; i++) {
console.log(fruit[i]);
}
Apple
Orange
Strawberry
Melon
Conclusion
Remember that indexes start at 0 meaning the last index will be one less than the array/string length.