How to add element to end of array - JavaScript

Mo Ibra

Mo Ibra

Jan 1, 2023

In this article we will learn how to add element at end of an array in JavaScript.

It is very common to add element at end of an array in JavaScript in JavaScript.


Problem

Now we have a problem, which is that we want to add an element at the end of the array.

Imagine we have a array like that:

const array = [1, 2, 3, 4, 5];

And we want to add an element at the end of this array.

Result will be like this

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

How to solve this problem?

In fact, the solution to this problem is very easy, and there is more than one solution to this problem.

  • Using push method
  • Using spread operator ...
  • Using concat method.

Add element at end using unshift method

We can use push method to add an element at the end of an array.

Example

// Array
const array = [1, 2, 3, 4, 5];

// Array unshift
array.push(6);

// Result:
console.log(array);

Output

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

The push() method adds one or more elements to the end of an array and returns the new length of the array. MDN


Add element at end using spread operator ...

We can use spread operator to solve this problem as well.

Let's see an example

// Array
const array = [1, 2, 3, 4, 5];

// Add element at the end of an array
const result = [...array, 6];

// Result:
console.log(result);

Output

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

The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. MDN


Add element at end using concat method

We can use concat method to solve this problem as well.

// Array
const array = [1, 2, 3, 4, 5];

// Add element at the end of an array
const result = array.concat([6])

// Result:
console.log(result);

Output

[0, 1, 2, 3, 4, 5];

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: