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

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

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳