The JavaScript array length property returns or sets the number of slots in an array. It is often the same as the number of elements, but arrays can contain empty slots, making the two values different.
- Returns the number of slots in an array.
- Can be used to truncate or extend an array.
- Empty slots are different from undefined and may be skipped by array methods.
let a = ["js", "html", "gfg"];
console.log(a.length);
Setting the Length of an Array
The length property can also be used to set the length of an array. It allows you to truncate or extend the array.
Truncating the Array
Setting the length property to a smaller value removes elements from the end of the array.
let a = ["js", "html", "gfg"];
a.length = 2;
console.log(a);
- The array a initially contains three elements.
- Setting a.length = 2 removes elements from the end of the array.
- Therefore, the output becomes ["js", "html"].
Extending an Array
Setting the length property to a larger value increases the array size by adding empty slots at the end.
let a = ["js", "html", "gfg"];
a.length = 5;
console.log(a);
- The array a initially contains three elements.
- Setting a.length = 5 extends the array by adding two empty slots at the end.
- Therefore, the output becomes ["js", "html", "gfg", <2 empty items>].
String Length Vs Array Length Property
String Length properly works same way, but we cannot modify length of a string as strings are immutable.
let a = ["js", "css", "html"];
a.length = 2; // Changes length of array
console.log(a);
let s = "geeksforgeeks"
s.length = 3; // Has no effect on string
console.log(s);
- The array a initially contains three elements.
- Setting a.length = 2 truncates the array, so the output becomes ["js", "css"].
- The string s is immutable, so s.length = 3 has no effect.
- Therefore, console.log(s) still outputs "geeksforgeeks".