In this tutorial, you will learn about the javascript array length method with the help of multiple examples.
The length method of the javascript array is used to calculate the length of the array and set the size of the array.
Also Read :
Example
let arr = ["uk", "usa", "india", "chine", "japan"];
let length = arr.length;
console.log(length);
//Output: 5
Array Length Syntax
Here is the syntax of the javascript array length()
method :
Return the length of the array :
arr.length;
Set the length of the array:
arr.length = number;
Here arr
is the array.
Array Length Return Value
arr.length()
returns the length of the array
Example 1: Using array length to find the length of the array
let countries = ["uk", "usa", "india", "chine", "japan"];
console.log(countries.length);
//Output: 5
let people = ["john", "boris"];
console.log(people.length);
//Output: 2
let empty = [];
console.log(empty.length);
//Output: 0
Output
5
2
0
Here, we can see the array length method which is returning different lengths for different arrays.
Example 2: Using array length in for loop
let countries = ["uk","usa","india","chine","japan"];
//array.length can be used to find
// the number of times a loop will run
for(let i = 0; i<countries.length; i++){
console.log(countries[i]);
}
Output
uk
usa
india
chine
Japan
Here we are using array length with the for loop to find out the number of times the loop will run.
Example 3: Using array length to set the array length
let countries = ["uk", "usa", "india", "chine", "japan"];
//truncate the array to 3 elements
countries.length = 3;
console.log(countries);
// Output: [ 'uk', 'usa', 'india' ]
//extended the array length to 7
countries.length = 7;
console.log(countries);
// Output: [ 'uk', 'usa', 'india', ]
Output
[ 'uk', 'usa', 'india' ]
[ 'uk', 'usa', 'india', <4 empty items> ]
Here we first truncated the array by decreasing its length then we extended its length to 7. You can see the 4 empty items in the program, these are the extra space that is created with the extension of the array length.
So that was all about the javascript array method. Hope you understood the concept of the array length method. If you still have any doubt left in your mind then please do ask in the comment section below.