- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Usage of rest parameter and spread operator in JavaScript?
Rest Parameter
With rest parameter, you can represent a number of arguments as an array. ES6 brought rest parameter to ease the work of developers. For arguments objects, rest parameters are indicated by three dots … and precedes a parameter.
Let’s see the following code snippet to define rest parameter −
<html> <body> <script> function addition(…numbers) { var res = 0; numbers.forEach(function (number) { res += number; }); return res; } document.write(addition(3)); document.write(addition(9,10,11,12,13)); </script> </body> </html>
Spread Operator
The spread operator will allow you to split an array into single arguments. These arguments are those, which are the functions as separate arguments.
Syntax
Here’s the syntax −
function myfunction(...iterableObj);
Here’s an example showing Spread Syntax with arguments:
function multiply(x, y) { return x*y; } var myArgs = [50, 100]; console.log(multiply(…myArgs));
Example
Here’s another example
<html> <body> <script> var a, b, c, d, e, f, g; a = [10,20]; b = "rank"; c = [30, "points"]; d = "run" // concat method. e = a.concat(b, c, d); // spread operator f = [...a, b, ...c, d]; document.write(e); document.write("<br>"+f); </script> </body> </html>
Advertisements