Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

Intro to the Spread Operator

The spread operator is one of my favorite features of es6. It allows us to pass values from an iterable object as arguments for something else.

The most common iterable objects include, arrays, and objects. We can pass in values from an array as arguments to a function

const arr = ['hello ', 'world'];

printArrayValues(...arr);

function printArrayValues(val1, val2) {
   console.log(val1, val2); // prints hello world
}

We can also use the spread operator to create new arrays with values containing from another array

const oldArr = [1,2,3,4,5];
const newArr [...oldArr, 6,7,8,9,10];
// or
const newArr2 = [-2, -1, 0, ...oldArr];

We can also use the spread operator on objects.

Here is an example of us creating a near identical of an object with just one key value being different

const original = {a: true, b:false, c:false};
const newObj = {...original, b: true};

Our new object will have a:true and c:false just like the old value, but now b will be set to true.