January 3, 2020

What are those three dots in Javascript?

Since ES6 a strange syntax has appeared in the code of our projects. Let’s see what does it means and how it can be used

Open your console and write an array with your favorite movies. If you log movies of course you will get the object you just created

let movies = ["The Searchers","Rio Bravo","Stagecoach"]
console.log(movies) // ["The Searchers", "Rio Bravo", "Stagecoach"]

But what happens if you log the same variable preceded by the three dots?

console.log(...movies) // The Searchers Rio Bravo Stagecoach

Now our array has turned into a list of single elements.

Let’s take an example with a string, it becomes list of characters

let movie = 'The Searchers'
// T h e   S e a r c h e r s

This syntax is called Spread operator and allows you to divide any iterable object into a list of single elements. Just as if we had used a for loop.

This is very powerful and allows you to do many things. For example combine arrays:

let movies = ["The Searchers", "Rio Bravo", "Stagecoach"]
let otherMovies = ["True Grit", "Red River"]

console.log([...movies, ...otherMovies])
//  ["The Searchers", "Rio Bravo", "Stagecoach", "True Grit", "Red River"]

or combine objects

let movieData = {director: "John Ford", year: 1948, distribution:"Warner Bros"}
console.log({name: "The Searchers", ...movieData})
// {name: "The Searchers", director: "John Ford", year: 1948, distribution: "Warner Bros"}

or still clone objects (just like Object.assign())

let movie = {name: "The Searchers", year: 1956}
let film = {...movie}

// {name: "The Searchers", year: 1956} This is a clone for movie!

It is particularly useful if used to pass arguments to functions because it allows us to pass an unknown and potentially unlimited number of elements. Normally a function is able to accept a precise number of arguments, we can provide it with more but it will be able to use only those expected. Let’s see an example:

function getBestMovies(a, ...b) {

getBestMovies("The Searchers","Rio Bravo","Stagecoach")
// The Searchers
// ["Rio Bravo", "Stagecoach"]

The first argument corresponds to the first element of the array, all the others end up inside the second argument as a new array. This syntax is called Rest parameters. Rest parameters can be destructured

function getBestMovies(...[a,b,c]) {
   console.log(`My favorites are ${a}, ${b} and ${c}`)

getBestMovies("The Searchers","Rio Bravo","Stagecoach")
// My favorites are The Searchers, Rio Bravo and Stagecoach

What? How is it possible? what does to deconstruct mean? Read the next post

If you’ve come to read this far you deserve a prize. Here’s the mythical “My rifle pony and me” song from Rio Bravo:

“Rio Bravo” John Ford 1950

No copyright / do whatever the hell you want with these contents
Built with Hugo and Kiss theme. Hosted on Netlify. Icons made by Ddara