×
☰ See All Chapters

TypeScript Array

An array is a homogenous ordered collection of elements of the same type. An array is a user-defined data type.

Declaring array

There are two general formats for array

Syntax

Example

let arr1: data_type[];

let numArray: number[];

let arr2: Array<data_type>;

let strArray: Array<string>;

data_type should be the data type of elements.

Initializing array

When initializing the array, values should match with the declared data type of array:

Syntax

Example

let arr1: number[] = [numericValue1, numericValue2, ...];

let numArray: number[] = [1.5, 2, 0x12];

let arr2: Array<string> = [stirnValue1, stirnValue2, ...];

let strArray: Array<string> = ['Manu', 'Advith'];

Accessing array element

Array elements can be accessed as array[index], where index is the position of the element in the array. Array index starts from 0. If you attempt to read an element beyond the array's size, undefined value will be returned.

let numArray: number[] = [1.5, 2, 0x12];

let strArray: Array<string> = ['Manu', 'Advith'];

 

let x: number = numArray[1]; // x = 2

let c: string = strArray[0]; // c = "Manu"

Size of an array can be obtained by accessing its length property.

let namArray: number[] = [1.5, 2, 0x12];

console.log(namArray.length); // prints 3

Array Destructuring

Suppose if you have to assign the first three values of array to three different variables we can do it as below:

let numArray: number[] = [1.5, 2, 0x12, 5, 3.9];

let a: number;

let b: number;

let c: number;

[a,b,c] = numArray;

How to iterate array

for loop

for loop can iterate through the elements of an array as below example:

let directions: string[] = ["north", "south", "east", "west"];

for(let i=0; i<3; i++) {

   console.log(directions[i]);

}

typescript-array-and-tupel-0

for..in loop

In for..in loop, the loop iterator takes the numeric index of the loop iteration, starting with 0.

Example:

let directions: string[] = ["north", "south", "east", "west"];

for(let i in directions) {

   console.log(directions[i]);

}

typescript-array-and-tupel-1

for..of loop

In for..of loop, the loop iterator takes the each value of the array one after the other, starting with first element.

Example:

let directions: string[] = ["north", "south", "east", "west"];

for(let i of directions) {

   console.log(directions[i]);

   console.log(i);

}

typescript-array-and-tupel-2

TypeScript Tupel

Tuple is similar to array but their elements can have different types. All the elements types must be declared in order in the declaration.

Example:

const t2: [string, number, boolean] = ['Manu', 100, true];

We cannot store the element of type different from its declaration.

 

All Chapters
Author