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:

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:

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:

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

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

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

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

Yatendrasinh Joddha
I am a software engineer currently living in Gandhinagar, India. My interest is in web and software development. I am also interested in sharing my knowledge with people.

I have expertise in asp.net and related Microsoft technologies, with JavaScript frameworks and libraries like JQuery, KnockOut.js,and AngularJS.
Yatendrasinh Joddha on FacebookYatendrasinh Joddha on GithubYatendrasinh Joddha on LinkedinYatendrasinh Joddha on TwitterYatendrasinh Joddha on Wordpress