JavaScript Array length
JavaScript array length property is used to set or return the number of elements in an array.
let a = ["js", "html", "gfg"];
console.log(a.length);
Output
3
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
let a = ["js", "html", "gfg"];
a.length = 2;
console.log(a);
Output
[ 'js', 'html' ]
Extending an Array
let a = ["js", "html", "gfg"];
a.length = 5;
console.log(a);
Output
[ 'js', 'html', 'gfg', <2 empty items> ]
size() vs length for finding length
Underscore.js defines a size method which actually returns the length of an object or array, but size is not a native method. So it is always recommended to use length property.
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);
Output
[ 'js', 'css' ] geeksforgeeks
JavaScript Array.length Property – FAQs
What is the length property in JavaScript arrays?
The length property in JavaScript arrays sets or returns the number of elements in the array. It is a read/write property.
Does the length property update automatically when elements are added or removed?
Yes, the length property automatically updates to reflect the number of elements in the array whenever elements are added or removed.
How does the length property behave with sparse arrays?
For sparse arrays (arrays with empty slots), the
lengthproperty counts all slots, including empty ones, which are considered undefined.
Does the length property impact performance?
Accessing or setting the
lengthproperty is a constant-time operation, and it is generally efficient. However, setting a very large length can lead to memory allocation and potential performance implications.
What is the maximum value the length property can hold?
The maximum value for the length property is 2^32 – 1 (4,294,967,295), as JavaScript arrays are indexed by 32-bit unsigned integers.


