Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to set default parameters in ES6 ?

  • Last Updated : 04 Dec, 2021

Function parameters with default values are initialized with default values if they contain no value or are undefined. JavaScript function parameters are defined as undefined by default. However, it may be useful to set a different default value. That is where default parameters come into play.

Syntax:

function name(parameter=value,...parameters) {

}

Example 1: If we multiply two numbers in this example without passing a second parameter and without using the default parameter, the answer that this function will return is NAN(Not a Number), since if we do not pass the second parameter, the function will multiply the first number with undefined.  

HTML




<script>
    function multiply(a, b) {
        return a * b;
    }
 
    let num1 = multiply(5);
    console.log(num1);
    let num2 = multiply(5, 8);
    console.log(num2);
</script>

Output:

NaN
40

Example 2: If we do not pass a number as the second parameter and take the default parameter as the second parameter, it will multiply the first number with the default number, and if we pass two numbers as parameters, it will multiply the first number with the second number.  

HTML




<script>
    function multiply(a, b = 2) {
        return a * b;
    }
 
    let num1 = multiply(5);
    console.log(num1);
    let num2 = multiply(5, 8);
    console.log(num2);
</script>

Output:

10
40

Example 3: Default Parameter with Constructor: we can use the default parameter concept with the constructor of a class.

HTML




<script>
    class Geeks {
        constructor(a, b = 3) {
            console.log(a * b);
        }
    }
    let obj = new Geeks(5);
    let obj1 = new Geeks(5, 4);
</script>

Output:

15
20

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!