Finding the length of arrays and strings in JavaScript

This tutorial explains how to find the length of an array (how many elements are in an array), the length of an element in an array, and the length of a string of text (how many characters in a string). You can watch the video below or click here to view it on YouTube.

Sometimes you might need to find out how many elements exist in an array (that is, the length of the array). The sample code below shows exactly how to do that, and it also shows you how to find the length of a string using pretty much the same method.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - More Arrays</title>
 <script type="text/javascript">
 
 var cars = new Array();
 
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // to find the length (number of elements) of an array we can use arrayname.length eg.:
 
 document.write(cars.length);
 
 /* 
 We could also use the length method on a string like this:
 
 var word = "hello";
 document.write(word.length);
 
 */
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Multidimensional arrays

Leave a Reply