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.
1. Add element at the end of array
To add an element at the end of an array we use push()
method.
Runnable example:
// ONLINE-RUNNER:browser;
var colors = ['Red', 'Yellow'];
colors.push('Green');
console.log(colors);
Output:
Red, Yellow, Green
2. Add element at the beginning of array
To add an element at the beginning of an array we use .unshift()
method.
Runnable example:
// ONLINE-RUNNER:browser;
var colors = ['Red', 'Yellow'];
colors.unshift('Green');
console.log(colors);
Output:
Green,Red,Yellow