EN
JavaScript - add element to array
3 points
In this article, we would like to show you how to add an element to an array in JavaScript.
To add an element at the end of an array we use push()
method.
Runnable example:
xxxxxxxxxx
1
var colors = ['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
var colors = ['Red', 'Yellow'];
2
colors.unshift('Green');
3
4
console.log(colors);
Output:
xxxxxxxxxx
1
Green,Red,Yellow