What will be the output? (Array Length)
Easy•
This problem demonstrates how setting the array.length property affects array contents.
Quick Navigation: Array.length Property • Comparison with Other Methods • Reference Behavior
Array.length Property
The length property of an array is writable. Setting it can truncate or extend the array.
Setting length to 0
let arr = [1, 2, 3, 4, 5, -6, 7];
arr.length = 0;
console.log(arr); // []What happens:
•Setting
arr.length = 0 removes all elements from the array•The array becomes empty but still exists
•This is equivalent to
arr = [] but modifies the existing array referenceOther length Manipulations
Truncating Array
let arr = [1, 2, 3, 4, 5];
arr.length = 3;
console.log(arr); // [1, 2, 3]Extending Array
let arr = [1, 2, 3];
arr.length = 5;
console.log(arr); // [1, 2, 3, empty × 2]
console.log(arr.length); // 5
console.log(arr[3]); // undefinedKey Points
1. Setting length < current length: Removes elements from the end
2. Setting length = 0: Clears the entire array
3. Setting length > current length: Creates empty slots (sparse array)
4. Empty slots are not the same as undefined values
Comparison with Other Methods
Different Ways to Clear an Array
Method 1: length = 0
let arr = [1, 2, 3];
arr.length = 0;
// arr is now []•Pros: Fast, modifies existing array
•Cons: Affects all references to the array
Method 2: Assignment
let arr = [1, 2, 3];
arr = [];
// arr is now []•Pros: Clear intent
•Cons: Creates new array, old references unchanged
Method 3: splice()
let arr = [1, 2, 3];
arr.splice(0, arr.length);
// arr is now []•Pros: Explicit
•Cons: Slower, more verbose
Method 4: pop() in loop
let arr = [1, 2, 3];
while (arr.length > 0) {
arr.pop();
}
// arr is now []•Pros: Works in all environments
•Cons: Very slow for large arrays
Reference Behavior
Important: Reference vs New Array
let arr1 = [1, 2, 3];
let arr2 = arr1; // arr2 references the same array
arr1.length = 0; // Modifies the shared array
console.log(arr2); // [] - arr2 is also empty!
// vs
let arr3 = [1, 2, 3];
let arr4 = arr3;
arr3 = []; // Creates new array, arr3 points elsewhere
console.log(arr4); // [1, 2, 3] - arr4 still has original valuesKey Difference:
•
arr.length = 0: Modifies the existing array (affects all references)•
arr = []: Creates a new array (only affects the variable, not other references)