How arrays works in TypeScript ?

Array in TypeScript is just similar to an array in other programming languages. The array contains homogeneous values means a collection of multiple values with different data types. TypeScript array is also fixed size, can not be resized once created. An array is a type of data structure that stores the elements of a similar data type and considers it as an object too.

How array work?

Array allocates in sequential memory blocks. Each memory block represents an array element. Elements of an array are accessed using the index of array elements for example to access 1st element of the array we need to access it using the 0th index as an index of an array starts from 0th index. Similarly, other elements get accessed using their index locations. 

How to declare array in TypeScript?

The array can be written in two ways:

Using the type of elements followed by [ ] to denote an array of that element type:

var list : number[] = [1,2,3,4,5];

Using generic array type:

var list : Array<number>=[1,2,3,4,5];

How to access array elements?

To access an element of a given array we must have to write array_name with a subscript.

Example:

Javascript
var arr : number [ ] = [1, 2, 3, 4, 5];

// Printing data
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[4]);

Output: 

1
2
3
5

Example: In this example the Array of numbers initialized. First and last elements displayed. Element added, removed, then array iterated to print elements.

JavaScript
let numbers: number[] = [1, 2, 3, 4, 5];

console.log("First element:", numbers[0]);
console.log("Last element:", numbers[numbers.length - 1]);

numbers.push(6);
console.log("Array after adding 6:", numbers);

numbers.pop();
console.log("Array after removing last element:", numbers);

console.log("Array elements:");
for (let num of numbers) {
    console.log(num);
}

Output:

"First element:",  1 
"Last element:", 5
"Array after adding 6:", [1, 2, 3, 4, 5, 6]
"Array after removing last element:", [1, 2, 3, 4, 5]
"Array elements:"
1
2
3
4
5

Contact Us