Default parameters in ES-6


Code for this and several other ES-6 features can be found in my github
ES-6 brings default character support to Javascript.
Let us first take a look at, how we would have implemented default parameters in ES-5:

var addThree = function(a,b,c){     
typeof a === 'undefined' ? a = 1 : a;     
typeof b === 'undefined' ? b = 2 : b;     
typeof c === 'undefined' ? c = 3 : c;     
console.log(a+b+c); 
}; 
We would have basically checked each and every parameter. If its value is not undefined, we would have taken the value of the variable, else would have set it to a default value.
This is made easier in ES-6 and default parameters can be used as follows:

var addThree = function(a= 1,b=2,c=3){     
console.log(a,b,c) 
};
If the function is invoked as :
addThree(); = > Then a, b and c would take default parameters as their values 1,2 and 3 respectively.
If the function is invoked as:
addThree(4,5); => Then a will take 4, b will take 5 and c will take the default parameter value 3.
Rule => Only the leading parameters can be optional.
This means once cant assign default parameter only to “c” without assigning default parameters for “a” and “b”. In other words, the following code will result in an error:

var addThree = function(a,b=2,c=3){     
console.log(a,b,c) 
};
It is also to be noted, that default parameters can be return value on a function. So, let us assume there is a function which increments and variable and returns its value as follows:

var a = 0;
var fn = function(){
return ++a;
};
A function can have its parameter’s default value as the return value of this function. For example:

var ff = function(a = fn()){
 console.log(a);
}
Each time function ff is called, it invokes function fn and gets the return value and assigns it to “a”.
The default parameters are evaluated only at run time unlike Python, where the function is evaluated only once.

Comments

Popular posts from this blog

Docker Commands

Dockerfile

ES-6 classes