How to add elements to an Array in TypeScript
How to add elements to an Array in TypeScript:
push method of array is used to add or append elements to the end of an array. This method adds items to the end of an array and returns the length.
In this post, we will learn how to use the push method with example.
Definition of push method:
push method is defined as like below:
push(e1, e2, e3.....en)
Where, e1, e2, etc. are elements to append to the array. This method appends these elements to the end of the array.
Return value of push:
push method returns the length of the newly created array.
Example of push method:
This is the same method available in JavaScript array. In TypeScript also, we can use this method in a similar way.
Let me show you an example:
let arr : string[] = new Array('one', 'two', 'three');console.log('Given array: ',arr);let len = arr.push('four');console.log('Length returned by push: ',len);console.log('New array: ',arr);
If you run this program, it will print the below output:
Given array: [ 'one', 'two', 'three' ]Length returned by push: 4New array: [ 'one', 'two', 'three', 'four' ]
- arr is the original array. We are using push to add one string to the array.
- The first log is printing the given array.
- The second log is printing the length that is returned by the push method. It is 4, i.e. the length of the newly created array.
- The third log is printing the newly created array.
Example 2: push with multiple elements:
We can also use push with more than one elements. Let's try to add 3 elements to the array using push:
let arr : string[] = new Array('one', 'two', 'three');console.log('Given array: ',arr);let len = arr.push('four', 'five', 'six');console.log('Length returned by push: ',len);console.log('New array: ',arr);
If you run, it will print:
Given array: [ 'one', 'two', 'three' ]Length returned by push: 6New array: [ 'one', 'two', 'three', 'four', 'five', 'six' ]
As you can see, the returned length is 6, i.e. the length of the new array.