🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

array.length

Reading time 1 min
Published Aug 10, 2017
Updated Oct 10, 2019

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.

Example
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:

Example
function mySample() {
    var cars = ["Audi", "BMW", "Toyota", "Mercedes"];
    cars.length = 7;
    document.getElementById("demo").innerHTML = cars.length;
}