In JavaScript, arrays are used to store multiple values in a single variable. The length property of an array is used to determine the number of elements in the array. Understanding how to work with the length property is essential for manipulating arrays effectively.
Syntax:
array.length
Examples:
1. Getting the length of an array:
let fruits = ['apple', 'banana', 'orange'];
console.log(fruits.length); // Output: 3
2. Modifying the length of an array:
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // Output: 5
numbers.length = 3; // Truncate the array
console.log(numbers); // Output: [1, 2, 3]
numbers.length = 7; // Extend the array
console.log(numbers); // Output: [1, 2, 3, undefined, undefined, undefined, undefined]
Explanation:
- The length property of an array returns the number of elements in the array.
- We can modify the length property to resize the array dynamically. If we increase the length, the array will be extended with 'undefined' elements, and if we decrease the length, the array will be truncated.