Last Updated : 11 Jul, 2025
JavaScript array length property is used to set or return the number of elements in an array.
JavaScript
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
JavaScript
let a = ["js", "html", "gfg"];
a.length = 2;
console.log(a);
Extending an Array
JavaScript
let a = ["js", "html", "gfg"];
a.length = 5;
console.log(a);
[ '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 properly works same way, but we cannot modify length of a string as strings are immutable.
JavaScript
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);
[ 'js', 'css' ] geeksforgeeks
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4