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;
}

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 09/03/2021
3176 People Used
Only 97 Left
Rating
5.0