Tuesday, 11 December 2018

What are the default parameters in JavaScript?

If you do not pass the arguments to a function, then the values of arguments are undefined.

HelloWorld.js
function sum(a, b){
    if(a == undefined || b == undefined){
        console.log("a : " + a + ", b : " + b);
        return;
    }
    return a + b;    
}

sum();
sum(10);
sum(20, 30);

Output
a : undefined, b : undefined
a : 10, b : undefined

You can add default values to the arguments. If you do not pass the arguments while calling the method, then these default values are used.

HelloWorld.js
function sum(a = 1, b = 1){
    return a + b;    
}

var x = sum();  //sum(1, 1)
var y = sum(10); //sum(10, 1)
var z = sum(20, 30);

console.log("x : " + x);
console.log("y : " + y);
console.log("z : " + z);

Output
x : 2
y : 11
z : 50


Previous                                                 Next                                                 Home

No comments:

Post a Comment