Arrays & spread syntax

May 26, 2022

MDN definition : Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

You didn't undestand anyhting ? Me neither ! Let see how to use the spread syntax with the following examples.

Merging arrays

let array1 = [1,2,3]
let array2 = [4.5.6]

let mergedArray = [...array1,...array2] //[1,2,3,4,5,6]

Cloning arrays

Array are passed by reference, not by value. The spread syntax is therefore an easy way to clone an array :

let array = [1,2,3]
let clonedArray = [...array] //[1,2,3]

Any changes made to either array wont be reflected to the other one. In other words, we have cloned them, not copied them.

Cloning an array is actually very useful when you want to use map it :

let array = [1,2,3]
let clonedArray = [...array]
clonedArray.map(value=>{return value*2}) //[2,4,6]

Secial case : transforming a string to an array of characters

let string = "Hello"
let array = [...string] //["H","e","l","l","o"]

"Erasing an array"

let array = [1,2,3]
let list = ...array //1,2,3

You would use this syntax to use the Math.min() or Math.max() functions :

let array = [1,2,3]
let max = Math.max(...array) //3

Profile picture

Written by Olivier Bonnet who lives and works in Montreal writing a blog that nobody reads 🤪...

© Bonneto 2024