In ES6, handling a parameter has become lot easier.
Your can passing a default parameter in function argument.
function funz(a, b = 5) {
console.log(a + b); //print 6
}
// Equivalent to: b === 5 if b is undefined or not passed
funz(1);
Converted as
function funz(a) {
var b = arguments.length <= 1 || arguments[1] === undefined ? 5 : arguments[1];
console.log(a + b); //print 6
}
// Equivalent to: b === 5 if b is undefined or not passed
funz(1);
From now on, converted venilla js code will not be added, Check the output in the demo link.
Passing a ...
resting parameter at end of the function argument means that last argument will be received as an array.
function funz(a, ...b) {
console.log(a, b); //print 1 [2, 3, 4]
}
funz(1, 2, 3, 4); // a = 1; b = [2, 3, 4]
Passing a ...
spread parameter in function argument means that passing each element of array as argument.
function funz(a, b, c, d) {
console.log(a); //print 1
console.log(b); //print 2
console.log(c); //print 3
console.log(d); //print 4
}
funz(...[1, 2, 3, 4]);