The length property of an array in JavaScript returns or sets the number of elements in that array. It is always one higher than the highest element defined in the array.
The syntax of Array.length property is:
length: number
This length property of Array gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
The length property can be used to get the number of elements in an array.
For example,
arr
with elements [1, 2, 3, 4, 5].length
property and store it in len
.len
to the console.const arr = [1, 2, 3, 4, 5];
const len = arr.length;
console.log(len);
5
The length property can be used to truncate an array.
For example,
arr
with elements [1, 2, 3, 4, 5].length
property to 3 to truncate the array.arr
to the console.const arr = [1, 2, 3, 4, 5];
arr.length = 3;
console.log(arr);
[1, 2, 3]
The length property can be used to extend the length of an array.
For example,
arr
with elements [1, 2, 3].length
property to 5 to extend the array.arr
to the console.const arr = [1, 2, 3];
arr.length = 5;
console.log(arr);
[1, 2, 3, <2 empty items>]
In this TypeScript tutorial, we learned about length property of Array: the syntax and few working examples with output and detailed explanation for each example.