In any programming language we often require having default parameter or default value for the parameter in a function. JavaScript allow us to initialize parameter a default value. If you are not passing any value to the parameter, then the default value of the parameter will be undefined.
Let’s consider below code:
function addition(num1, num2) { return num1 + num2; } addition();
Here, you are calling function “addition()” in which you are not passing any parameter. So, the default value for the parameters “num1” and “num2” will be set to undefined.
Now in past if you want to set a default value to the “num1” and “num2” you have to do it like:
function addition(num1, num2) { if(num1 === undefined){ num1 = 10; } if(num2 === undefined){ num2 = 20; } return num1 + num2; } addition();
In ECMA 2015 features ECMAScript 6 has introduced a default parameter feature, in which it allows us to set default value to the parameter of a function. So for the function “addition()” if you want to assign a parameters with default values, you have to write below code:
function addition(num1 = 10, num2 = 20) { return num1 + num2; } addition();
In above code while calling function “addition()” we are not passing any parameter. So, as we have assigned default values to the parameters, “num1” will be assigned value 10 and “num2” will be assigned a value 20 so the function will return the answer “30”.
Experiment 1: Passing an Undefined
function addition(num1 = 10, num2 = 20) { return num1 + num2; } addition(undefined, undefined);
In above code we are passing “undefined” for both arguments of the function, so the function again will return the answer “30”.
Experiment 2: Passing an Parameter in Parameter
function addition(num1 = 10, num2 = num1 + 10) { return num1 + num2; } addition();
In above code we are passing “num1” as a value to the “num2”. This will work fine, and the function will return an answer “30”.
Experiment 3: Passing a function in Parameter
function addition(num1 = 10, num2 = getValue()) { return num1 + num2; } function getValue() { return 20; } addition();
In above code we are calling a function “getValue()” to assign a default value to the parameter “num2”. When we will call function “addition()”, at run time function “getValue()” will be called and value 20 will be assigned to the parameter “num2”. So, the function will return an answer 30.
Interested in JavaScript? Click here to read more JavaScript articles in Code4Developers
I have healthy knowledge and experience in Azure, O365 and ASP.Net with c#, MVC, WebApi along with client-side frameworks and libraries like JavaScript, JQuery, KnockoutJs, AngularJs, Angular, ReactJs, NodeJs
3 comments
The problem is the js default param not working on Safari
Yes, as default parameter is ECMASCRIPT 2015 feature many browser does not support it yet. Safari is one of them
Experiment 3: Passing a function in Parameter is really an interesting one