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 (how many characters in a string). This can be quite useful in programming, for example, if you wanted to:
- find out how many items a player has in the inventory in a game (checking the length of an inventory array)
- find out how many products are in a user’s shopping cart in an online shopping app (checking the length of a shopping cart array)
- check that a user’s password is long enough for increased security (checking length of a password stored as a string)
Watch the video below and scroll down to see the sample code:
Here is the sample HTML code:
<html> <head> <title>Finding the length of arrays and strings</title> <script src="script.js"></script> </head> <body> </body> </html>
And here is the sample JavaScript code:
// Create an array var cars = ["BMW", "Volkswagen", "Toyota", "Audi"]; // Use the length method to find the length of the array // The length of an array is the number of elements it contains var numberofcars = cars.length; console.log(numberofcars); // Create a string var password = "oranges"; // Use the length method to find the length of the string // The length of a string is how many characters it contains var passwordlength = password.length; console.log(passwordlength); // We can also find the length of an individual string element in an array // by referring to the index of the element console.log(cars[1].length);
Next tutorial: Multidimensional arrays