AppDividend
Latest Code Tutorials

Javascript Rest Operator Example | ES6 Tutorial

0 195

Get real time updates directly on you device, subscribe now.

Javascript Rest Operator Example | ES6 Tutorial is today’s topic. The Rest Operator syntax allows us to represent an indefinite number of arguments as an array. Rest operator is an improved way to handle the function parameters, letting us to more efficiently handle various input as parameters in the function.

Javascript Rest Operator Example

See the following syntax for Javascript Rest Operator.

function f(x, y, ...args) {
  // ...
}

One thing to remember is that only the last parameter can be a “Rest Parameter.”

Let us see the following example.

// app.js

const sum = (...args) => {
	return args.reduce((a, b) => a + b);
};

console.log(sum(1, 3, 5, 7, 9));

In the above example, we have provided the five arguments, and when it calls the sum function, we have used the rest operator to bundle those arguments into an array. Then we have reduced that array and return the output. Finally, the output is following.

 

Javascript Rest Operator Example | ES6 Tutorial

There are three main differences between the rest parameters and an argument object.

  • The rest parameters are the ones that haven’t been given the separate name (i.e., formally defined in function expression), while an argument object contains all arguments passed to the function;
  • The argument object is not a real array, while rest parameters are the Array instances, meaning methods like sort, mapforEach or pop can be applied to it directly.
  • An argument object has additional functionality specific to itself (like the callee property).

Let’s see the following example where we take an argument as a string and see the following example.

// app.js

const funcString = (a, b, ...manyMoreArgs) => {
	console.log('a', a); 
	console.log('b', b);
	console.log('manyMoreArgs', manyMoreArgs); 
};

funcString('mia', 'despacito', 'attention', 'wolves', 'sorry');

Here, one thing to remember that is the rest parameter is last in the argument list. The output is following.

 

Javascript Rest Operator Example

Array Merge using Spread Operator

We can merge the arrays using the spread operator.

Let’s see the following example.

// app.js

let arr = [19, 20, 21];
let arr2 = [4, 16];
let merged = [...arr,...arr2];

console.log(merged);

In the above example, we get the merged array items in the output.

 

ES6 Tutorial With Example From Scratch

If you don’t know about Spread Operator, then check out this article.

Finally, Javascript Rest Operator Example | ES6 Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.