Spread vs rest operators
š©āš» <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.