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: 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.



✐ 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,

  1. Create an array arr with elements [1, 2, 3, 4, 5].
  2. Get the length of the array using the length property and store it in len.
  3. Log len to 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,

  1. Create an array arr with elements [1, 2, 3, 4, 5].
  2. Set the length property to 3 to truncate the array.
  3. Log the modified array arr to 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,

  1. Create an array arr with elements [1, 2, 3].
  2. Set the length property to 5 to extend the array.
  3. Log the modified array arr to 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.