Open In App

JavaScript Array length

Last Updated : 16 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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);

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

JavaScript
let a = ["js", "html", "gfg"];
a.length = 2;

console.log(a);

Output
[ 'js', 'html' ]

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



Next Article

Similar Reads