EN
TypeScript - add element to array
0 points
In this article, we would like to show you how to add an element to an array in TypeScript.
To add an element at the end of an array we use push()
method.
Runnable example:
xxxxxxxxxx
1
const colors: string[] = ['Red', 'Yellow'];
2
colors.push('Green');
3
4
console.log(colors);
Output:
xxxxxxxxxx
1
[ 'Red', 'Yellow', 'Green' ]
To add an element at the beginning of an array we use .unshift()
method.
Runnable example:
xxxxxxxxxx
1
const colors: string[] = ['Red', 'Yellow'];
2
colors.unshift('Green');
3
4
console.log(colors);
Output:
xxxxxxxxxx
1
[ 'Green', 'Red', 'Yellow' ]