The length property used on arrays in JavaScript is useful for determining how many elements are contained in an array.
This property is also used to determine the length of a string.
The syntax is very simple: ArrayName.length.
Where with nomeaArray we indicate the array of which you want to calculate the length.
JavaScript array length – example 1
Let’s look at a very simple first example of this JavaScript property.
Given an array, determine its length.
So let’s suppose we have an array containing the following elements:
var schoolObjects = ['eraser', 'notebook', 'pencil'];
We then apply the length property of JavaScript on this array and we will get as a result 3, which corresponds to the number of elements.
var lengthArray = schoolObjects.length;
console.log(lengthArray);
Consequently, if I want, for example, to print the first and last element of the array, I can write:
console.log(schoolObjects[0]);
console.log(schoolObjects[2]);
Or, if I don’t know the length of the array, I can also write:
console.log(schoolObjects[0]);
console.log(schoolObjects[lengthArray - 1]);
In fact, by subtracting the value 1 from the length of the array, I always get the last element.
JavaScript array length – example 2
We create an array of elements and then display each element using the for loop.
This second example is similar to the previous one but uses the length property on the array as a condition of the for loop.
So I create the array in this way:
var schoolObjects = ['eraser', 'notebook', 'pencil'];
Then I scroll through the array through a simple for loop, stopping when the variable counter i is less than days.length.
In fact, as observed in the previous example, the last element has the position days.length – 1, which in our specific case has the value 2.
Here is the useful for loop to scroll through the array and print each element on the web page.
for (var i=0; i < schoolObjects.length; i++) {
document.write(schoolObjects[i] + “
”);
}
Conclusion
In this lesson we have analyzed some examples of using the JavaScript array length property, in the next lessons we will deal with other examples with the use of this property.