Search in Help for developer site.

Thursday 27 September 2018

Rest parameter in Javascript


What is Rest parameter in Javascript.

Rest parameter is a modern feature of Javascript that allows a function to store multiple arguments in a single array.
It is similar to param keyword in C#.

Lets understand it by an example.


function sendOrders(...allOrderIds)
{
    allOrderIds.forEach(id=>console.log(id));
}

sendOrders(100,200,300);

//output
//100 200 300


...allOrderIds is a rest parameter. In sendOrders function we are passing three integer and all will be stored in allOrderIds array.

We can send any number of parameter in Rest parameter.





Rest parameter with normal parameter:


function sendOrders(day,...allOrderIds)
{
    allOrderIds.forEach(id=>console.log(id));
}
sendOrders('Monday',100,200,300);

Rest parameter should be the last parameter in a function:


function sendOrders(...allOrderIds,day) //Error
{
    allOrderIds.forEach(id=>console.log(id));
}

Above code will throw an error saying "comma is not permitted after the rest element", because rest parameter should be last parameter.


Difference between let and var keyword in javascript

Let and Var keyword in Javascript

Let and var keywords are used to declare variable in Javascript.

When to use Let over var keyword in Javascript.

It is recommended to use Let keyword over var keyword in javascript. Lets see why

Example 1: Declaration scope

In the below example, if we use let keyword and use the variable before its declaration it gives an error. Which is absolutely fine. 
console.log(orderId);  //Gives an error
let orderId = 10;

Now if we use var keyword and try to use the variable before its declaration it doesn't give any error. Which is strange. Not Recommended.
console.log(orderId); //undefined(not an error)
var orderId = 10;

Example 2: Scope in code block

Here let variable is bound to if block
if (true) {
let orderQty = 10;
}
console.log(orderQty);  //Error, Out of scope

var keyword is not bound to if block you can use outside the if block.
if (true) { 
var orderQty = 10;
}
console.log(orderQty);  //it will print 10, No error

So it is best practice to use let keyword over var keyword for declaring variable in Javascript.