JavaScript Array Length: Main Tips
- You can use the JavaScript
length
property to return the array length. - The
length
property sets the length of arrays as well.
Returning and Setting Array Length
The array.length
property returns the length of array in JavaScript.
function mySample() {
var cars = ["Audi", "BMW", "Toyota", "Mercedes"];
document.getElementById("demo").innerHTML = cars.length;
}
Tip: this property for getting array length in JavaScript can count not defined values.
The JavaScript length
property can change the number of elements arrays have.
However, if you simply indicate that the array length shifts from 3 to 4, the property creates an extra non-iterable empty spot.
Follow this example to use JavaScript to set length of arrays:
function mySample() {
var cars = ["Audi", "BMW", "Toyota", "Mercedes"];
cars.length = 7;
document.getElementById("demo").innerHTML = cars.length;
}