Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

JavaScript Array.length Property

Posted on December 16, 2024 By Admin No Comments on JavaScript Array.length Property

The Array.length property is a built-in property representing the number of elements in an array. It is a dynamic property that updates automatically whenever elements are added or removed from the array.

Syntax

array.length

Return Value

The length property returns a non-negative integer that specifies the number of elements in the array.

Example 1: Getting the Length of an Array

let arr = [10, 20, 30, 40, 50];

console.log(arr.length); // Output: 5

Example 2: Using length in a Loop

let arr = [10, 20, 30, 40, 50];

for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
// Output:
// 1
// 2
// 3
// 4
// 5

Example 3: Dynamically Updating the Array Length

let arr = [10, 20, 30, 40, 50];

arr.length = 3;
console.log(arr);        // Output: [10, 20, 30]
console.log(arr.length); // Output: 3

Setting the length property to a smaller value truncates the array, removing elements beyond the specified length.

Example 4: Expanding the Array Length

let arr = [10, 20, 30];

arr.length = 5;
console.log(arr);        // Output: [10, 20, <3 empty items>]
console.log(arr.length); // Output: 5

When the length property is set to a value greater than the current array size, new slots are added as empty items.

Example 5: Modifying length to Clear an Array

let arr = [10, 20, 30, 40, 50];

arr.length = 0;
console.log(arr);        // Output: []
console.log(arr.length); // Output: 0

Example 6: Adding Elements Beyond Current Length

let arr = [10, 20, 30];

arr[5] = 60;
console.log(arr);        // Output: [10, 20, 30, <2 empty items>, 60]
console.log(arr.length); // Output: 6

Adding an element at an index beyond the current length automatically adjusts the length property.

Supported Browsers

BrowserSupport
Chrome1+
Firefox1+
Safari1+
Edge12+
Opera4+
Internet Explorer5.5+
JavaScript, Web Technologies Tags:JavaScript-Array, JavaScript-Array-Property

Post navigation

Previous Post: Sort Array of Objects by String Property Value in JavaScript
Next Post: JavaScript Array sort() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • JavaScript
  • Lodash
  • PHP
  • Python
  • Web Technologies
  • Web Templates

Recent Posts

  • JavaScript Array isArray() Method
  • JavaScript Array forEach() Method
  • JavaScript Array includes() Method
  • JavaScript Array keys() Method
  • JavaScript Array lastIndexOf() Method

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme