JavaScript Default Parameters

JavaScript Default Parameters with Examples

In this article, I am going to discuss JavaScript Default Parameters with Examples. Please read our previous article where we discussed JavaScript Object Literals with Examples.

What are JavaScript Default Parameters?

JavaScript ES6 introduced new features of Default parameters. In any programming language, we sometimes require having a default parameter or default value for the parameter in a function. JavaScript ES6 allows specifying default values to the function parameters.

The name Default parameters are self-explanatory that if nothing is provided the default one is applied. Default parameters are a pretty easy way to make our code aligned by integrating default parameter values directly into the function header instead of handling them within the function’s body.

Arguments VS Parameters in JavaScript

Let’s start first by understanding the difference between arguments and parameters. These 2 terms are used frequently when dealing with functions. But by definition parameters are what we define in the function declaration whereas the arguments are what we pass into the function. Consider the below example.

Example: JavaScript argument vs parameters

Run the below example and open the browser developer’s tool and see the output.

<html>
<head>
    <title>JavaScript argument vs parameters example</title>
</head>
<body>
    <script>
        function sum(a, b) {
            return a + b;
        }

        var result = sum(100, 200);
        console.log(`The result is ${result}`);
    </script>
</body>
</html>

Output: The result is 300

In this example, the a and b are the parameters of the sum() function, and the values that we passed to the sum() function 100 and 200 are the arguments.

Default Parameters in JavaScript

In JavaScript ES6, Default function parameters allow named parameters to be initialized with default values. If no value or undefined is passed.

In JavaScript, the default value of function parameters is undefined, which means if we are not passing any value or arguments into the function parameter, its parameters will have the default value of undefined. However, it’s often useful to set a different default value. This is where default parameters can help.

Syntax to use Default Parameters in JavaScript

Following is the syntax to use Default Parameters in JavaScript

Syntax to use Default Parameters in JavaScript

Example: JavaScript function default parameters
<html>
<head>
    <title>JavaScript function default parameters Example</title>
</head>
<body>
    <script>
        //ES5
        function ES5addNumbers(a, b, c) {
            if (b === undefined)
                b = 7;
            if (c === undefined)
                c = 31;
            return a + b + c;
        }
        let ES5_AddNoResults = ES5addNumbers(2) === 40//true
        console.log('ES5 default parameters check: ', ES5_AddNoResults); //true

        //ES6
        const ES6addNumbers = (x, y = 7, z = 31) => {
            return x + y + z;
        }
        let ES6_AddNoResults = ES6addNumbers(2) === 40//true
        console.log('ES6 default parameters check: ', ES6_AddNoResults); //true
    </script>
</body>
</html>
Output:

JavaScript function default parameters Example

Features of JavaScript Default Parameters
  • Function default parameters allow named parameters to be initialized with default values. If no value or undefined is passed.
  • We can pass in default parameters in functions. This is useful as having a default for a function can provide a safeguard for an application.
  • We can also call a function and use the value returned by the function as a default parameter
  • Earlier declared parameters can be reused as a default value for the upcoming parameters’ values.
  • The default value expression is evaluated at function call time from left to right
  • Use default params in ES6 to enforce required parameters.
Where to use Default Parameters in JavaScript?

The default parameter is applied in two and only two situations:

  • When No parameter provided
  • When an undefined parameter provided

In other words, if we pass in null the default parameter won’t be applied.

Note: Default value assignment can be used with de-structured parameters as well (see de-structured article to see an example)

Set a default parameter value for a JavaScript function:

ES5 default parameters

In ES5, the common way for setting defaults value to a parameter was to test parameter values in the function body and assign a default value if they are undefined. Earlier default parameter values used to integrate within the function’s body to make our code compact. Before ECMAScript 2015 (ES6), in ES5 a parameter’s default value could be assigned in the following way.

How it works without default parameters:
Example:

If we didn’t pass the arguments into the multiplyNos(). If no value is provided for num1 and num2 when multiplyNos is called, num1 and num2 value would be undefined by default. When evaluating num1* num2 the function is going to multiply undefined by undefined and multiplyNos would return NaN in the output. Because the function is trying to multiply two things that are not a number.

<html>
<head>
    <title>JavaScript ES5 function default parameters Example</title>
</head>
<body>
    <script>
        //before ES6
        function multiplyNos(num1, num2) {
            console.log({ num1 }, typeof num1);
            console.log({ num2 }, typeof num2);
            return num1 * num2
        }

        console.log(`before ES6 multiplyNos function without any parameter: ${multiplyNos()}`); //NAN
    </script>
</body>
</html>
Output:

Set a default parameter value for a JavaScript function

Example:

If we passed the 10 into the multiplyNos(). If no value is provided for num2 when multiplyNos is called, num1 value would be 10 and num2 value would be undefined by default. When evaluating num1* num2 the function is going to multiply the number by undefined and multiplyNos would return NaN in the output.

<html>
<head>
    <title>JavaScript ES5 function default parameters Example</title>
</head>
<body>
    <script>
        //before ES6
        function multiplyNos(num1, num2) {
            console.log({ num1 }, typeof num1);
            console.log({ num2 }, typeof num2);
            return num1 * num2
        }

        console.log(`before ES6 multiplyNos function with one parameter: ${multiplyNos(10)}`); //NAN
    </script>
</body>
</html>
Output:

JavaScript Default Parameters with Examples

Example:

If we passed 10 and 20 into the multiplyNos(). If the value is provided for num1 and num2, the default value will not be considered. when multiplyNos is called, num1 and num2 value would be 10 and 20. When evaluating num1* num2 the function is going to multiply number by number and multiplyNos would return 200 in the output.

<html>
<head>
    <title>JavaScript ES5 function default parameters Example</title>
</head>
<body>
    <script>
        //before ES6
        function multiplyNos(num1, num2) {
            console.log({ num1 }, typeof num1);
            console.log({ num2 }, typeof num2);
            return num1 * num2
        }

        console.log(`before ES6 multiplyNos function with all parameters: ${multiplyNos(10, 20)}`); //200 
    </script>
</body>
</html>
Output:

What are JavaScript Default Parameters?

We looked at the problem of not having a default parameter and then we will take a look at how default values for function parameters address that problem with different alternative

In past, if we want to set a default value to either num1 or num2 or both, we have to do it like this. To guard against this, something like the second example would be used, where num2 is set to 1 as default if multiplyNos() is called with only one argument using the Conditional ternary (?) operator. We discussed the Conditional ternary (?) operator in detail in our Operator article.

How it works with default parameters:

Let us first see the example and then we will try to understand the code.

<html>
<head>
    <title>JavaScript ES5 function default parameters using ternary operator Example</title>
</head>
<body>
    <script>
        //before ES6
        function multiplyNos(num1, num2) {
            console.log({ num1 }, typeof num1);
            console.log({ num2 }, typeof num2);

        //ES5 default parameter values used to integrate within the function’s body using ternary operator
            num2 = (typeof num2 !== 'undefined') ? num2 : 1 //default value=1
            return num1 * num2
        }

        console.log(`before ES6 multiplyNos function without any parameter: ${multiplyNos()}`);//NAN
        console.log(`before ES6 multiplyNos function with one parameter: ${multiplyNos(10)}`);//10
        console.log(`before ES6 multiplyNos function with all parameters: ${multiplyNos(10, 20)}`);//200
    </script>
</body>
</html>
Output:

JavaScript Default Parameters

In the first function call, we didn’t pass the arguments into the multiplyNos(). If no value is provided for num1 and num2 when multiplyNos is called, num1 and num2 value would be undefined by default. When evaluating num1* num2 the function is going to multiply undefined by 1 (num2 is undefined and hence the default value is going to be set as 1) and multiplyNos would return NaN in the first output. Because the function is trying to multiply two things where one is not a number.

In the second function call, we passed the 10 into the multiplyNos(). If no value is provided for num2 when multiplyNos is called, num1 value would be 10 and num2 value would be 1 by default. When evaluating num1* num2 the function is going to multiply 10 and 1 and multiplyNos would return 10 in the second output.

In the third function call, we passed the 10 and 20 into the multiplyNos(). If the value is provided for num1 and num2, the default value will not be considered. when multiplyNos is called, num1 and num2 value would be 10 and 20. When evaluating num1* num2 the function is going to multiply number by number and multiplyNos would return 200 in the third output.

Setting Default Value using Logical Operator (||) in JavaScript

In past, if we want to set a default value to either num1 or num2 or both, we have to do it like this. Another way of this, something like the third example would be used, where num1 and num2 are set to 0 as default if multiplyNos is called with only one or without any argument using Logical OR (||) operator. We discussed the Logical OR (||) operator in detail in our Operator article.

Example: JavaScript ES5 function default parameters using Logical OR || operator
<html>
<head>
    <title>JavaScript ES5 function default parameters using Logical OR || operator Example</title>
</head>
<body>
    <script>
        //before ES6
        function multiplyNos(num1, num2) {
            console.log({ num1 }, typeof num1);
            console.log({ num2 }, typeof num2);

        //ES5 default parameter values used to integrate within the function’s body using logical OR operator
            num1 = num1 || 0; //default value=0
            num2 = num2 || 0; //default value=0
            return num1 * num2
        }

        console.log(`before ES6 multiplyNos function without any parameter: ${multiplyNos()}`);//0
        console.log(`before ES6 multiplyNos function with one parameter: ${multiplyNos(10)}`);//0
        console.log(`before ES6 multiplyNos function with all parameters: ${multiplyNos(10, 20)}`);//200
    </script>
</body>
</html>
Output:

Setting Default Value using Logical Operator (||) in JavaScript

Another Approach of Setting Default Value in JavaScript

In past, if we want to set a default value to the num1 and num2, we have to do it like this. One more way of this, something like the fourth example would be used, where num1 and num2 are set to 0 as default if multiplyNos is called with only one or without any argument. In ES5, the common way for setting defaults value to a parameter was to test parameter values in the function body and assign a default value if they are undefined.

Example: JavaScript ES5 function default parameters Example
<html>	
<head>
    <title>JavaScript ES5 function default parameters Example</title>
</head>
<body>
    <script>
        //before ES6
        function multiplyNos(num1, num2) {
            console.log({ num1 }, typeof num1);
            console.log({ num2 }, typeof num2);

        //ES5 default parameter values used to integrate within the function’s body
            if (num1 === undefined)
                num1 = 5;
            if (num2 === undefined)
                num2 = 3;
            return num1 * num2
        }

        console.log(`before ES6 multiplyNos function without any parameter: ${multiplyNos()}`);//15
        console.log(`before ES6 multiplyNos function with one parameter: ${multiplyNos(10)}`);//30
        console.log(`before ES6 multiplyNos function with all parameters: ${multiplyNos(10, 20)}`);//200
    </script>
</body>
</html>
Output:

Default Parameters in JavaScript with Examples

We looked at the problem of not having default parameters and then we took a look at how default values for function parameters address that problem with the different alternatives. Traditionally, we would pass values in the function but now it has become much easy to create a default value and pass it as a part of the parameters in the function.

ES6 Default Parameters in JavaScript

In ES6, Default parameters are a pretty easy way to make our code aligned by integrating default parameter values directly into the function header instead of handling them within the function’s body. In ES6 with default parameters, checking the default parameter values in the function body are no longer necessary. Now, we can assign 1 as the default value for num2 in the function header.

In the second function call, we passed the 10 into the multiplyNos(). If no value is provided for num2 when multiplyNos is called, num1 value would be 10 and num2 value would be 1 by default. When evaluating num1* num2 the function is going to multiply number by number and multiplyNos would return 10 in the second output. What we discussed above is given in the below example.

Example: JavaScript ES6 function default parameters
<html>
<head>
    <title>JavaScript ES6 function default parameters Example</title>
</head>
<body>
    <script>
        //in ES6 default parameter values used to integrate in the function header
        function multiplyNos(num1, num2 = 1) { //num2 default value=1
            console.log({ num1 }, typeof num1);
            console.log({ num2 }, typeof num2);
            return num1 * num2
        }

        console.log(`In ES6 multiplyNos function without any parameter: ${multiplyNos()}`);//NAN
        console.log(`In ES6 multiplyNos function with one parameter: ${multiplyNos(10)}`);//10
        console.log(`In ES6 multiplyNos function with all parameters: ${multiplyNos(10, 20)}`);//200
    </script>
</body>
</html>
Output:

ES6 Default Parameters in JavaScript

We can also set a default value for all parameters of the function. In the first function call, we didn’t pass the arguments into the multiplyNos(). If no value is provided for num1 and num2 when multiplyNos is called, num1 and num2 value would be 5 and 3 by default. When evaluating num1* num2 the function is going to multiply number by number and multiplyNos would return 15 in the first output.

In the third function call, we passed the 10 and 20 into the multiplyNos(). If the value is provided for num1 and num2, the default value will not be considered. when multiplyNos is called, num1 and num2 value would be 10 and 20. When evaluating num1* num2 the function is going to multiply number by number and multiplyNos would return 200 in the third output. What we discussed above is given in the below example.

Example: JavaScript ES6 function default parameters
<html>
<head>
    <title>JavaScript ES6 function default parameters Example</title>
</head>
<body>
    <script>
        //in ES6 default parameter values used to integrate in the function header
        function multiplyNos(num1 = 5, num2 = 3) { //num1 & num2 default value=5,3
            console.log({ num1 }, typeof num1);
            console.log({ num2 }, typeof num2);
            return num1 * num2
        }

        console.log(`In ES6 multiplyNos function without any parameter: ${multiplyNos()}`);//15
        console.log(`In ES6 multiplyNos function with one parameter: ${multiplyNos(10)}`);//30
        console.log(`In ES6 multiplyNos function with all parameters: ${multiplyNos(10, 20)}`);//200
    </script>
</body>
</html>
Output:

Features of JavaScript Default Parameters

This proved that if a parameter is missing when the function is invoked, its value is kept as undefined, which we tested in the first function call, we didn’t pass the arguments into the multiplyNos(). As it can be confirmed by explicitly providing arguments which we saw in the third function call we passed the 10 and 20 into the multiplyNos(), overwriting the default one with the explicitly provided arguments. Let’s look at some available options for setting default values of the function parameters in JavaScript with Examples.

Passing undefined vs. other falsy values in JavaScript

Default parameters are one of the most useful features in JavaScript. Basically, when we don’t provide a value to a function argument then the default values are considered as its value. Before passing the undefined, null, and other falsy values. Let us first understand what are they and what values they hold.

  1. Undefined: Undefined means the variable is declared but has not assigned any value, has the value undefined.
  2. null: null is a value that shows there is not value or absence of value.
  3. Falsy: values in JavaScript are categorized into truthy or falsy. Falsy value is a value that evaluates to FALSE

There are only 6 falsy values in JavaScript

Passing undefined vs. other falsy values in JavaScript

Example: function default parameters without passing undefined and falsy values
<html>
<head>
    <title>JavaScript ES6 function default parameters without passing undefined and falsy values Example</title>
</head>
<body>
    <script>
        //in ES6 default parameter without passing undefined and falsy values
        //arrow function
        defaultFunc = (a = 0, b = 0, c = 0) => {
            console.log({ a }, typeof a);
            console.log({ b }, typeof b);
            console.log({ c }, typeof c);
            return a, b, c;
        }

        console.log(`In ES6 defaultFunc function without any parameter: ${defaultFunc()}`);//0,0,0
        console.log(`In ES6 defaultFunc function with one parameter: ${defaultFunc(1)}`);//1,0,0
        console.log(`In ES6 defaultFunc function with two parameters: ${defaultFunc(1, 2)}`);//1,2,0
    </script>
</body>
</html>
Output:

function default parameters without passing undefined and falsy values

Here, in the first function call defaultFunc() no value is provided so a default value 0, b default value 0 and c default value 0 is assigned to a, b, c respectively in defaultFunc(). In the third function call defaultFunc(1, 2) we don’t have value for the last argument c so 0 is taken as default. What if we don’t have value for the first/second argument, then should we use null or undefined in that place. Let’s try the same example with undefined and null in places where we don’t have values.

Example: function default parameters passing undefined and falsy values
<html>
<head>
    <title>JavaScript ES6 function default parameters passing undefined and falsy values Example</title>
</head>
<body>
    <script>
        //in ES6 default parameter, passing undefined and falsy values
        //arrow function
        defaultFunc = (a = 0, b = 0, c = 0) => {
            console.log({ a }, typeof a, { b }, typeof b, { c }, typeof c);
            return a, b, c;
        }

        //undefined
        console.log(`In ES6 defaultFunc function passing undefined as 3rd argument: ${defaultFunc(1, 2, undefined)}`);//1,2,0
        console.log(`In ES6 defaultFunc function passing undefined as 2nd argument: ${defaultFunc(1, undefined, 2)}`);//1,0,2
        console.log(`In ES6 defaultFunc function passing undefined as 1st argument: ${defaultFunc(undefined, 1, 2)}`);//0,1,2

        //null
        console.log(`In ES6 defaultFunc function passing null as 3rd argument: ${defaultFunc(1, 2, null)}`);//1,2,null
        console.log(`In ES6 defaultFunc function passing null as 2nd argument: ${defaultFunc(1, null, 2)}`);//1,null,2
        console.log(`In ES6 defaultFunc function passing null as 1st argument: ${defaultFunc(null, 1, 2)}`);//null,1,2
    </script>
</body>
</html> 
Output:

Where to use Default Parameters in JavaScript?

As we can see, undefined produced the expected results. As we saw ES6 default parameters take default value if no value or undefined is passed. As JavaScript automatically uses undefined if we don’t pass any argument whereas null gave a different outcome as null is an explicit value that tells there is no value hence the outcome is null. Because “undefined is a variable declared but not assigned a value”, but “null is a value assigned”. But both of them return a falsy value when used in an if condition.

Evaluating Default Parameters at Call Time in JavaScript

JavaScript evaluates the default value expression at the time we call the function from left to right. A new object is created each time the function is called. Also, each time we call an array without an argument, a new instance of an empty array is created. What we discussed above is given in the below example.

Example: Evaluating default parameters at call time in JavaScript
<html>
<head>
    <title>JavaScript ES6 function Evaluating default parameters at call time Example</title>
</head>
<body>
    <script>
        function SavingFuc(rupees, bankArray = []) {
            bankArray.push(rupees)
            return bankArray
        }

        console.log('Evaluating default parameter without any argument: ', SavingFuc()); // [undefined] empty array
        console.log('Evaluating default parameter with argument value 10: ', SavingFuc(10));  // [10]
        console.log('Evaluating default parameter with argument value 20: ', SavingFuc(20)); // [20], not [10, 20]          
    </script>
</body>
</html>
Output:

Evaluating Default Parameters at Call Time in JavaScript

These features even can be applied to functions and variables.

Example: Evaluating default parameters at call time using the function in JavaScript
<html>
<head>
    <title>JavaScript ES6 function Evaluating default parameters at call time using function Example</title>
</head>
<body>
    <script>
        function callIncrementFunc(count = increment()) {
            return count
        }

        let numberOfTimesCalled = 0
        function increment() {
            numberOfTimesCalled += 1
            return numberOfTimesCalled
        }

        console.log(`Evaluating default parameter using function call ${callIncrementFunc(0)} times`);
        console.log(`Evaluating default parameter using function call ${callIncrementFunc(1)} times`);
        console.log(`Evaluating default parameter using function call ${callIncrementFunc(1)} times`);        
    </script>
</body>
</html>
Output:

Evaluating default parameters at call time using function in JavaScript

The callIncrementFunc() function takes one parameter count whose default value is the returned value of the increment() function. The increment() function returns number of times called. When we declared the callIncrementFunc() function, the increment() function has not yet evaluated until we called the callIncrementFunc() function.

Use default params in ES6 to enforce required parameters

This is some cool trick that we can do with the default parameters.

Require Parameter check: The Default parameters allow us to require an argument to be passed to the function. In short, we can use default params for enforcing required parameters.

We can create a function that throws an error and assign it as a default value for required parameters. We can use this feature to make arguments are mandatory. If the caller doesn’t pass any argument, we can throw an error. What we discussed above is given in the below example.

Example: JavaScript ES6 function Require Parameter check to throw an error
<html>
<head>
    <title>JavaScript ES6 function Require Parameter check to throw an error Example</title>
</head>
<body>
    <script>
        const requiredArg = () => {
            throw new TypeError("You did not pass the required argument.")
        }

        const greeting = (name = requiredArg()) => console.log(`Hello ${name}!`);

        greeting();// returns "Uncaught TypeError: You did not pass the required argument."
        greeting('Kathy'); //return "Hello Kathy!"
    </script>
</body>
</html>
Output:

The below output throws an error when we call the greeting() function without any argument.

Use default params in ES6 to enforce required parameters

The below output will come after commenting on the first function call and then calling the greeting() function with Kathy as an argument

Hello Kathy!

What we have discussed above is explained below using another example with two required params check to throw an error.

Example: JavaScript ES6 function two Require Parameters check to throw an error
<html>
<head>
    <title>JavaScript ES6 function two Require Parameters check to throw an error Example</title>
</head>
<body>
    <script>
        function throwIfMissing() {
            throw new Error('You have a missing param!');
        }
        function addition(requiredParam1 = throwIfMissing(), requiredParam2 = throwIfMissing()) {
            console.log('The addition of 10, 20 is: ', requiredParam1 + requiredParam2);
        }

        addition(10); // Returns- Uncaught Error: You have a missing param
        addition(10, 20); // Returns -The addition of 10, 20 is:  30
    </script>
</body>
</html>
Output:

The below output throws an error when we call the addition() function with only one argument.

JavaScript ES6 function two Require Parameters check to throw an error

The below output will come after commenting on the first function call and then calling the addition() function with 10 and 20 as a required argument

The addition of 10, 20 is: 30

Using other parameters in default values/ Earlier parameters are available to later default parameters/ Evaluated Left to Right

Default value expressions are evaluated at function call time from left to right. This also means that default expressions can use the values of previously-filled parameters.

Example: JavaScript ES6 function default parameters- Evaluated Left to Right
<html>
<head>
    <title>JavaScript ES6 function default parameters- Evaluated Left to Right example1</title>
</head>
<body>
    <script>
        function findPerson(gender, person = 'Kathy Angel', respect = person + ' Good' + ' ' + gender) {
            return [gender, person, respect]
        }

        console.log('Evaluating default parameter from left to right with gender param', findPerson('woman')); // ["woman", "Kathy Angel", "Kathy Angel Good woman"]
        console.log('Evaluating default parameter from left to right with gender and person param', findPerson('man', 'John Doe')); // ["man", "John Doe", "John Doe Good man"]
    </script>
</body>
</html>
Output:

Using other parameters in default values/ Earlier parameters are available to later default parameters/ Evaluated Left to Right

As we can see in the above example, we can reuse a param on the left i.e.: gender and person as a default param for something on the right i.e.: respect param. Note that respect will get the gender and person param with the default check applied.

Example: JavaScript ES6 function default parameters- Earlier parameters are available to later default parameters
<html>
<head>
    <title>JavaScript ES6 function default parameters- Earlier parameters are available to later default parameters example</title>
</head>
<body>
    <script>
        //sample code1
        function sum(x = 1, y = x, z = x + y) {
            return x + y + z;
        }
        console.log('sample code#1');
        console.log('Earlier parameters are available to later default parameters without param: ', sum()); // 4
        console.log('Earlier parameters are available to later default parameters with 5 as param: ', sum(5));//20

        //sample code2
        let zero = 0;
        function multiply(x) { return x * 2; }
        function addMultiply(a = 1 + zero, b = a, c = b + a, d = multiply(c)) {
            console.log((a + b + c), d);
        }
        console.log('sample code#2');
        console.log('Earlier parameters are available to later default parameters with one param=1: ', addMultiply(1)); // 4, 4
        console.log('Earlier parameters are available to later default parameters with one param=3: ', addMultiply(3)); // 12, 12
        console.log('Earlier parameters are available to later default parameters with 2 params=2,7: ', addMultiply(2, 7)); // 18, 18
        console.log('Earlier parameters are available to later default parameters with 3 params=1,2,5: ', addMultiply(1, 2, 5)); // 8, 10
        console.log('Earlier parameters are available to later default parameters with 4 params=1,2,5,8: ', addMultiply(1, 2, 5, 8)); // 8, 8
    </script>
</body>
</html>
Output:

JavaScript ES6 function default parameters- Earlier parameters are available to later default parameters

In the sum() function:

  1. The default value of the y parameter is set to the x parameter.
  2. The default value of the z parameter is the sum of the x and y parameter
  3. The sum() function returns the sum of x, y, and z.
Scope Effects in JavaScript

In function default parameters, the function parameter list has its own scope. That means if we provide a reference of the parameter that has not been initialized yet, on attempting to reference that parameter, we will get a Reference Error.

Example: JavaScript ES6 function default parameters- scope effect
<html>
<head>
    <title>JavaScript ES6 function default parameters- scope effect Example</title>
</head>
<body>
    <script>
        function Subtract(a = b, b = 1) {
            return a - b;
        }
        console.log('Default parameters Scope effect: ', Subtract()); //Uncaught ReferenceError: Cannot access 'b' before initialization
        console.log('Default parameters Scope effect: ', Subtract(20)); //19
    </script>
</body>
</html>
Output:

The below output throws a Reference Error when we call the Subtract() function without any argument. Because in the function we are referencing b as a default value to a parameter, which has not yet initialized yet hence on attempting to refer JavaScript thrown an error. This error will be triggered only when we don’t pass the parameter when the function is invoked.

JavaScript ES6 function default parameters- scope effect

The below output will come after commenting on the first function call and then calling the Subtract() function with 20 as an argument

Default parameters Scope effect: 19

Using function’s return value as default value in JavaScript

In the ES6 default parameter, we can also call a function and use the value returned by the function as a default value for a parameter.

Example: JavaScript ES6 function default parameters- Using function’s return value as default value
<html>
<head>
    <title>JavaScript ES6 function default parameters- Using function’s return value as default value Example</title>
</head>
<body>
    <script>
        let taxRate = () => 0.13;
        let calculateBill = function (price, tax = price * taxRate(), tip = 0.15) {
            return price + (price * tax) + (price * tip);
        }

        console.log('Using function’s return value as default-use the default value: ', calculateBill(100)); //1415
        console.log('Using function’s return value as default-explicitly pass values: ', calculateBill(100, .05, .2)); //125
        console.log('Using function’s return value as default-pass price + tip, let tax use default: ', calculateBill(100, undefined, .20)); //1420
    </script>
</body>
</html>
Output:

JavaScript ES6 function default parameters- Using function’s return value as default value

In the above example:

  1. In the first function call calculateBill() we didn’t pass any parameter except price as 100 so as to use the default value of tax and tip parameters. Hence the output is 1415.
  2. In the second function call calculateBill() we explicitly pass the value of the parameter hence the output is 125.
  3. In the third function call calculateBill() we pass the price and tip parameters value and for tax, we pass undefined which will use the tax default value. Hence the output is 1420.
The argument object with length and value in JavaScript

The argument object represents the length and the value. Argument object with length(arguments.length): the value of the argument object within the function body represents the number of arguments passed to the function.

Argument object value (arguments): The argument array object only holds the parameters which doesn’t contain default value rather they hold the values that are explicitly defined at the time of function call. What we discussed above is given in the below example.

Example: JavaScript ES6 function default parameters- using argument object
<html>
<head>
    <title>JavaScript ES6 function default parameters- using argument object example</title>
</head>
<body>
    <script>
        function argFun(x, y = 8, z = 42) {
            console.log('Argument length: ', arguments.length, ' Argument value: ', arguments)
            return x + y + z;
        }

        console.log('Using argument object argFunc() with 1 argument: ', argFun(5)); //
        console.log('Using argument object argFunc() with 2 argument: ', argFun(5, 10)); //
        console.log('Using argument object argFunc() with 3 argument: ', argFun(5, 20, 25)); //
    </script>
</body>
</html>
Output:

JavaScript ES6 function default parameters- using argument object

The default value for JavaScript Data types

Below are some functions created with the default value for each data type

Example: JavaScript function Default value for JavaScript Data types
<html>
<head>
    <title>JavaScript function Default value for JavaScript Data types example</title>
</head>
<body>
    <script>
        const defaultNumber = (number = 25) => console.log('Number default value: ', number)
        const defaultString = (string = 'Javascript') => console.log('String default value: ', string)
        const defaultBoolean = (boolean = true) => console.log('Boolean default value: ', boolean)
        const defaultObject = (object = { year: 2021 }) => console.log('Object default value: ', object)
        const defaultArray = (array = [10, 20, 30]) => console.log('Array default value: ', array)
        const defaultNull = (nullValue = null) => console.log('Null default value: ', nullValue)

        console.log(defaultNumber());
        console.log(defaultString());
        console.log(defaultBoolean());
        console.log(defaultObject());
        console.log(defaultArray());
        console.log(defaultNull());
    </script>
</body>
</html>
Output:

JavaScript function Default value for JavaScript Data types

Here, in this article, I try to explain JavaScript Default Parameters with Examples. I hope this JavaScript Default Parameters with Examples article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *