Spread vs rest operators

Xena Coder
1 min readSep 18, 2018

--

šŸ‘©ā€šŸ’» <h2>Hello, fellas</h2>

Hope you are doing well. Today I will explain you how to deal with ā€œā€¦ā€ functionality and get its difference; usually itā€™s used as a **spread operator** or as a **rest parameter**. Letā€™s take a look at examples:

Rest parameters

function add(num1, num2) {
return num1 + num2;
}

add(1, 2, 4, 5) // returns 3

Bang šŸ¤”, it sucks.. pure JS doesnā€™t cope with a task properly. Letā€™s userest parameters and try to gather many arguments into an array.

function add(ā€¦args) {
let sum = 0;
for( let arg of args) sum += arg;

return sum
}
add(1, 2) // 3
add(1, 2, 3, 4) //10

We did it šŸ˜

PAY ATTENTION: Rest parameters have to be at the last argument.

Spread operators

This tool helps us to spread expand elements. Letā€™s see:

const fruits = [ā€˜appleā€™, ā€˜bananaā€™, ā€˜lemonā€™];
const meal =[ā€¦fruits, ā€˜onionā€™, ā€˜breadā€™];
console.log(meal) // ā€˜appleā€™, ā€˜bananaā€™, ā€˜lemonā€™, ā€˜onionā€™, ā€˜breadā€™

Notice that you can use the spread operator as the first argument unlike rest parameters. Also you can easily copy the an array:

const arr1 = [ā€˜chocolateā€™, ā€˜lolipopā€™];
const arr2 = [ā€¦arr1];
console.log(arr2) // ā€˜chocolateā€™, ā€˜lolipopā€™

Awesome !!!

The last hack Iā€™d rather share with you: you can pass an array as a list of arguments into a function:

function add(a, b, c) {
return a + b + c;
}
const nums = [1, 2, 3];

add(ā€¦nums) // 6

Hope this article helped you to simplify understanding spread and rest operators ā¤ and its difference.

--

--

Xena Coder
Xena Coder

Written by Xena Coder

Frontend developer. Master of Sports in Powerlifting and Weightlifting

No responses yet