TypeScript Array length
Syntax & Examples
Array.length property
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.
Syntax of Array.length
The syntax of Array.length property is:
length: numberThis 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.
✐ Examples
1 Using length to get the size of an array
The length property can be used to get the number of elements in an array.
For example,
- Create an array
arrwith elements [1, 2, 3, 4, 5]. - Get the length of the array using the
lengthproperty and store it inlen. - Log
lento the console.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
const len = arr.length;
console.log(len);Output
5
2 Using length to truncate an array
The length property can be used to truncate an array.
For example,
- Create an array
arrwith elements [1, 2, 3, 4, 5]. - Set the
lengthproperty to 3 to truncate the array. - Log the modified array
arrto the console.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
arr.length = 3;
console.log(arr);Output
[1, 2, 3]
3 Using length to extend an array
The length property can be used to extend the length of an array.
For example,
- Create an array
arrwith elements [1, 2, 3]. - Set the
lengthproperty to 5 to extend the array. - Log the modified array
arrto the console.
TypeScript Program
const arr = [1, 2, 3];
arr.length = 5;
console.log(arr);Output
[1, 2, 3, <2 empty items>]
Summary
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.