DEV Community

Cover image for Javascript: Spread Operators CheetSheet
imsabir
imsabir

Posted on

Javascript: Spread Operators CheetSheet

You might have heard about this Spread Operators and be are using it too in everyday Developement.

Syntax: (...)

Definition: According to MDN Web Docs

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.

Use case scenario: We will see this with comparing normal arrays method, so this can be helpful to everyone including who didn't used it as well as who is also familiar with it.

1. String to Array with Spread:

const myName = "Jhon Doe";
const convertMyNameToArray = [...myName];
console.log(convertMyNameToArray);
//Output: Array (8)[ J,h,o,n, ,D,o,e ]

Enter fullscreen mode Exit fullscreen mode

2. Spread for Merging Array:


const array1 = [50,150,250];
const array2 = [100,200,300];
const mergedArray = [
  ...array1,
  ...array2
]
console.log(mergedArray);
//Output: Array(6)[ 50,150,250,100,200,300 ]
Enter fullscreen mode Exit fullscreen mode

3. Cloning Array using Spread:

//Without Spread Operator:
const animals = ['lion','tiger','zebra'];
const wildAnimals = animals;

wildAnimals.push('elephant')
console.log(animals);
//Output: Array (4)[ lion,tiger,zebra,elephant ]
//Here original array is affected although we pushed in cloned array.


//With Spread Operator:
const animals = ['lion','tiger','zebra'];
const wildAnimals = [...animals];
wildAnimals.push('elephant');
console.log(animals)
//Output: Array (3)[ lion,tiger,zebra ]
//Here original array is NOT affected

Enter fullscreen mode Exit fullscreen mode

Do you know why it behave like this? Stay tune I am brining another blog for explaining this. Why seprate blog? because required to understand the concepts of data types and its right now out of context of this blog.

4. Set Object to Array

//Creating a new Set Object
const flowersSet = new Set(['rose','lotus','lilly']);
console.log(flowersSet);
//Output: Set (3) { rose=> rose,lotus=> lotus,lilly=> lilly }


//Converting the Set Object to Array
const newFlowerArray = [...flowersSet];
console.log(newFlowerArray);
//Output: Array (3)[ rose,lotus,lilly ]
Enter fullscreen mode Exit fullscreen mode

5. Nodelist to Array:

//create nodelist object
const h1s = document.querySelectorAll('h1');

//convert nodelist to an array
const h1sArray = [...h1s];

Enter fullscreen mode Exit fullscreen mode

5. Min or Max value from an array:

//USING APPLY
const ages = [21,52,55]
const elderPerson = Math.min.apply(Math,ages); //21
const younderPerson = Math.max.apply(Math,ages); //55

//USING Spread
const elderPerson = Math.min(...ages); //21
const younderPerson = Math.max(...ages); //55

Enter fullscreen mode Exit fullscreen mode

Spread Operator for Objects:

const user1 = {
    name: 'Jhon',
    age: 21,
};

const user2 = {
    name: "Doe",
    dob: "5th Jan 1990" 
};

const mergedUsers = {...user1, ...user2};
console.log(mergedUsers)
//Output: {name: 'Doe', age: 21, dob: '5th Jan 1990'}
Enter fullscreen mode Exit fullscreen mode

Follow @msabir for more such updates.

Cheers!

Top comments (9)

Collapse
 
parenttobias profile image
Toby Parent

I tend to think of the spread operator as being on the right side of an assignment, and the rest operator as being on the left... but it can get foggy:

const capitalize = ([firstLetter, ...restOfWord])=>firstLetter.toUpperCase()+restOfWord.join('').toLowerCase();

console.log(capitalize("heLlO") ); // 'Hello'
Enter fullscreen mode Exit fullscreen mode

In this case, we're using the rest operator, but we're implicitly spreading the string into an array!

Collapse
 
msabir profile image
imsabir • Edited

Actually, Rest and Spread are part of one umbrella but working is Opposite to each ohter. In short:

The three dots in JavaScript are the spread / rest operator. The spread syntax allows an expression to be expanded in places where multiple arguments are expected.
The rest parameter syntax is used for functions with a variable number of arguments. The spread / rest operator for arrays was introduced in ES6

Rest Operator: collects all remaining elements or rest Item into an array.
When used in function arguments of a function declaration/expression it will convert
the remaining arguments into an array. This variant is called the Rest parameters
syntax.

function rest(first, second, ...remainder) {
  console.log(remainder);
}

// 30, 40 ,50 are the remaining parameters and will be 
// merged together in to an array called remainder 
rest(10, 20, 30, 40, 50);
Enter fullscreen mode Exit fullscreen mode

Will cover in deep in future blogs.

Cheers!!

Collapse
 
parenttobias profile image
Toby Parent

my own lazy understanding, rest happens on the assignment (left-hand) side, while spread happens on the evaluation (right-hand) side. Any time we're ... in an assigment to something (like a parameter), we're using rest.

Collapse
 
mattthecuber profile image
MattTheCuber

That's such a clever one liner

Collapse
 
parenttobias profile image
Toby Parent

lol I love finding things that are elegant, clear, and concise. It says exactly what it's doing, from the parameter signature to the return. Makes me happy. :D

Collapse
 
harshjoeyit profile image
Harshit Gangwar

Yes, I have the same understanding.

Collapse
 
harshjoeyit profile image
Harshit Gangwar

Awesome!
I'd like to give a suggestion.
Screen shot of code snippet with syntax highlighting would be more readable.
Cheers!

Collapse
 
msabir profile image
imsabir

Stay tune for next blog !!

Collapse
 
palharez profile image
Palharez

Nice topic!!