Spread Operator and Rest Operator Example in JavaScript

Hi Everyone,

In this blog i am going to discuss about array destructuring javascript. I'm going to talk about Spread Operator, Rest Operator and Destructuring in JavaScript, and as I have been working on JavaScript since 4 years, I used to think that spread operator is used for destructuring.

While working on a project in react js app recently I found out that concept of destructuring is completely different and thought of sharing it here. So, Let's begin.

Spread Operator

The spread operator in JavaScript is used to split up array elements or object properties. It is the features of ES6 and It does deep cloning of the array elements or object, so it doesn't affect the original values.
Let's see the Example of Array first:

const arr1 = [1, 2, 3]
const arr2 = [...arr1, 4, 5]
console.log(arr1);              // [1, 2, 3]
console.log(arr2);              // [1, 2, 3, 4, 5]
arr1.push(6, 7);
console.log(arr1);              // [1, 2, 3, 6, 7]
console.log(arr2);              // [1, 2, 3, 4, 5]

 

Look We can see above that arr2 hasn't changed after adding more values to arr1. But what if I hadn't provided the "..." operator in arr2. Let's find out below with an example

const arr1 = [1, 2, 3]
const arr2 = [arr1, 4, 5]
console.log(arr1);              // [1, 2, 3]
console.log(arr2);              // [[1, 2, 3], 4, 5]

 

Same goes with the objects. See the example code to understand:

const obj1 = {
  name: "Prince",
  Sex: "Male"
}
console.log(obj1);        //{name: "Prince", sex: "male"}

const obj2 = {
  ...obj1,
age: 25              //{age: 25, name: "Prince", sex: "male}
}
console.log(obj2);

obj1["height"] = "5'8 ft";
console.log(obj1);//{height: "5'8 ft",name: "Prince", sex: "male"}
console.log(obj2);   //{age: 25, name: "Prince", sex: "male}

 

Rest Operator

Rest operator is used in a function whenever multiple arguments are expected using spread operator.

const filter = (...args) => {
  return args.filter(val => val%5===0)
}

console.log(filter(5, 10, 2, 4, 20));    // [5, 10, 20]

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.