Home » Posts » Spread operator in JavaScript

Spread operator in JavaScript

As per MDN

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.

Let’s understand it using examples

Expanding strings

const whoAmI = "I am Spider-Man";
console.log(whoAmI);
console.log('Array of chars', [...whoAmI]);
I am Spider-Man
Array of chars [
  'I', ' ', 'a', 'm',
  ' ', 'S', 'p', 'i',
  'd', 'e', 'r', '-',
  'M', 'a', 'n'
]

Expanding arrays

const avengers = ['Iron Man', 'Captain America', 'Hulk', 'Hawkeye', 'Black Widow'];
console.log(avengers);
console.log(...avengers);
[ 'Iron Man', 'Captain America', 'Hulk', 'Hawkeye', 'Black Widow' ]
Iron Man Captain America Hulk Hawkeye Black Widow

Concatenating arrays

const array1 = ['et', 'tu'];
const array2 = ['brute'];
const concatenated = [...array1, ...array2];
console.log(concatenated);
[ 'et', 'tu', 'brute' ]

Copying arrays

const yesterdaysList = ['bread', 'eggs', 'vegetables', 'milk'];
const todaysList = [...yesterdaysList];
console.log(todaysList);
[ 'bread', 'eggs', 'vegetables', 'milk' ]

Shallow copying objects

const commandoDroid = {
    appearance: 'Star Wars: The Clone Wars',
    affiliations: 'Confederacy of Independent Systems',
    height: '1.91m',
    weapon: 'Blaster Rifle'
};
const droid1 = { ...commandoDroid, name: 'Droid 1' };
const droid2 = { ...commandoDroid, name: 'Droid 2' };
console.log(droid1, droid2);
{
  appearance: 'Star Wars: The Clone Wars',
  affiliations: 'Confederacy of Independent Systems',
  height: '1.91m',
  weapon: 'Blaster Rifle',
  name: 'Droid 1'
} {
  appearance: 'Star Wars: The Clone Wars',
  affiliations: 'Confederacy of Independent Systems',
  height: '1.91m',
  weapon: 'Blaster Rifle',
  name: 'Droid 2'
}

Variable length arguments

function sum(...args) {
    let sum = 0;

    for (let x of args) {
        sum += x;
    }

    return sum;
}
console.log(sum(1, 2, 3, 4, 5, 6, 7));
28

Leave a Reply

Your email address will not be published.