M
MeshWorld.
JavaScript Tutorial 1 min read

How to add an element to ending of an array with ES6

Vishnu Damwala
By Vishnu Damwala

The spread operator ..., introduced first in ES6 became one of the most popular and favourite feature among the developers.

A separate RFC was made for this much widely accepted feature to extend its functionalities to objects, prior it only worked on arrays.

This tutorial describes how to add element to the ending of an array using spread operator in ES6

Example with animals emoji

let animals = ["๐Ÿฆ", "๐Ÿต", "๐Ÿ•", "๐ŸฆŠ", "๐Ÿฏ"];
console.log(animals);
// Output โ†’ ["๐Ÿฆ", "๐Ÿต", "๐Ÿ•", "๐ŸฆŠ", "๐Ÿฏ"]

console.log(animals.length);
// Output โ†’ 5

animals = [...animals, "๐Ÿฆ„"];

console.log(animals.length);
// Output โ†’ 6

console.log(animals);
// Output โ†’ ["๐Ÿฆ", "๐Ÿต", "๐Ÿ•", "๐ŸฆŠ", "๐Ÿฏ", "๐Ÿฆ„"]

// now with multiple elements
animals = [...animals, "๐Ÿ†", "๐Ÿฆ“", "๐Ÿผ", "๐Ÿฆ˜"];

console.log(animals.length);
// Output โ†’ 10

console.log(animals);
// Output โ†’ ["๐Ÿฆ", "๐Ÿต", "๐Ÿ•", "๐ŸฆŠ", "๐Ÿฏ", "๐Ÿฆ„", "๐Ÿ†", "๐Ÿฆ“", "๐Ÿผ", "๐Ÿฆ˜"]

Happy coding