JavaScript Array length (original) (raw)
Last Updated : 16 Nov, 2024
**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);
`
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.
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);
`
Output
[ 'js', 'css' ] geeksforgeeks