How to add an element to an array in javascript ?

Published: March 02, 2022

Updated: December 09, 2022

Tags: Javascript; Array;

DMCA.com Protection Status

Examples of how to add an element to an array in javascript:

Add an element at the end of an array using push()

Let's create a simple array:

var A = [1,2,3,4];

console.log( A );

gives

[1, 2, 3, 4]

To append a new element at the end a solution is to use push(). An example, add the element 5 to the matrix A:

A.push(5);

console.log( A );

gives

[1, 2, 3, 4, 5]

var A = [1,2,3,4];
var B = [5,6];

A.push(B);

console.log( A );

gives

[1, 2, 3, 4, Array(2)]

Concatenate two arrays in javascript

To cancatenate two arrays in javascript, a solution is to use Array.prototype.concat()

var A = [1,2,3,4];
var B = [5,6];

A = A.concat(B);

console.log( A );

gives

[1, 2, 3, 4, 5, 6]

Insert a new element for a given index using splice() in javascript

To insert a new element, a solution is to use splice(index,0,'new element'):

var A = ['a','b','c','d'];

A.splice(3, 0, "Hello");

console.log( A );

gives

['a', 'b', 'c', 'Hello', 'd']