Logo


Spread operator in javascript


(...) These three dots are called spread operator in javascript which as the name represents, it allows an expression to be expanded. Spread operator is very handy while working with objects and arrays in javascript. This is also called es6 spread operator becuase it is included in es6.


1var parts = ['two', 'three'];
2var numbers = ['one', ...parts, 'four', 'five']; // ["one", "two", "three", "four", "five"]

The three dots represent the spread operator in ES6. It allows us to do quite a few things in JavaScript:

1.Concatenate arrays

1var shooterGames = ['Moiz', 'hassan', 'Resident Evil'];
2 var racingGames = ['Need For Speed', 'Gran Turismo', 'Burnout'];
3 var games = [...shooterGames, ...racingGames];
4 console.log(games)  // ['Moiz', 'hassan', 'Resident Evil',  'Need For Speed', 'Gran Turismo', 'Burnout']

2.Destructuring an array

1 var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil'];
2   var [first, ...remaining] = shooterGames;
3   console.log(first); //Call of Duty
4   console.log(remaining); //['Far Cry', 'Resident Evil']}

3:Combining two objects

1function myFuction(a, b, c) {
2    console.log("a:", a, ", b:", b, ", c:", c);
3  }
4  let arr = [1, 2, 3];
5  myFuction(...arr); // a:1, b:2, c:3

Function arguments as array


There's another use spread operator which is known as Rest Parameters and it makes it possible to take all of the arguments to a function in as one array.

1function myFuction(a, b, c) {
2    console.log("a:", a, ", b:", b, ", c:", c);
3  }
4  let arr = [1, 2, 3];
5  myFuction(...arr); // a:1, b:2, c:3


Related Articles :

Javascript objects

Javascript arrays



About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share