;

How to Set Default Values for Function Parameters in Javascript


Tutorialsrack 28/06/2021 Jquery Javascript

In this article, you’ll learn how to set default values for function parameters in JavaScript. The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined).

In a function, if a parameter value is not provided, then its value becomes undefined. In this case, the default value of the parameter that we specify is applied by the compiler.

Default parameter values have been introduced in ES6 in 2015, and are widely implemented in modern browsers.

Sometimes this is acceptable, but in some cases, it is better to assign a default value to the parameter.

Example 1: Parameter without Default Value

Let’s take a look at an example without a default value parameter:

Example 1: Parameter without Default Value
function doSomething(message) {
    console.log(message);
}
 
doSomething();
//Output is: 'undefined'
 
doSomething("Hello, Tutorialsrack");
//Output is: "Hello, Tutorialsrack"

In the above example, you’ll clearly see if we do not pass the parameter value it will return undefined and if we pass the value then it will return the passed value.

Example 2: Parameter With Default Value

Let’s take a look at an example parameter with a default value: 

Example 2: Parameter With Default Value
function doSomething(message = "hi") {
    console.log(message);
}
 
doSomething();
//Output is: 'hi'
 
doSomething("Hello, Tutorialsrack");
//Output is: "Hello, Tutorialsrack"

In the above example, you’ll clearly see if we do not pass the parameter value it will return the default parameter value and if we pass the value then it will return the passed value.

I hope this article will help you to understand how to set default values for function parameters in JavaScript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags