The Wayback Machine - https://web.archive.org/web/20230722162953/https://www.geeksforgeeks.org/how-to-declare-the-optional-function-parameters-in-javascript/
Skip to content
Related Articles
Open In App

Related Articles

How to declare the optional function parameters in JavaScript ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we will see how to declare optional function parameters in JavaScript. There are two approaches to do so:

Using the Logical OR operator (‘||’): In this approach, the optional parameter is Logically OR is used with the default value within the body of the function. 

Note: The optional parameters should always come at the end of the parameter list. 

Syntax:

function myFunc(a,b) {
  b = b || 0;
  // b will be set either to b or to 0.
}

Example: In the following program the optional parameter is ‘b’: 

html




function check(a, b) {
    b = b || 0;
    console.log("Value of a is: " + a +
        " Value of b is: " + b);
}
check(5, 3);
check(10);

Output: 

Value of a is: 5 Value of b is: 3
Value of a is: 10 Value of b is: 0

Using the Assignment operator (“=”): In this approach the optional variable is assigned the default value in the declaration statement itself. Note: The optional parameters should always come at the end of the parameter list. 

Syntax:

function myFunc(a, b = 0) {
   // function body
}

Example: In the following program the optional parameter is ‘b’: 

html




function check(a, b = 0) {
    console.log("Value of a is: " + a +
        " Value of b is: " + b);
}
check(9, 10);
check(1);

Output: 

Value of a is: 9 Value of b is: 10
Value of a is: 1 Value of b is: 0
Last Updated : 22 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials