Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

JavaScript Default Parameters

The JavaScript default Parameters option was added in the ES6 version of JavaScript. In this tutorial let us learn What is a default Parameter and how to use them in JavaScript

Default Parameters

The Default Parameters allows us to initialize the parameter with default values if no value or undefined is passed as the argument

Need for Default Parameters

JavaScript allows us to pass any number of arguments to a function irrespective of the number of parameters declared by the function

For Example, take a look at the following JavaScript function. We can invoke it without any argument addNum() or with a single argument addNum(1). JavaScript does not prevent us from doing so.

When we do not pass any argument, the JavaScript assigns the value undefined to the parameters. Hence we get NaN as the result.

                            
function addNum(a, b) {
    return a + b ;
}
 
//Both a & b is initialzed as undefined
console.log(addNum());              //Nan
 
//b is initialzed as undefined
console.log(addNum(1));             //Nan
 
 
//OK
console.log(addNum(1,2));           //3
 
                            
                        
                            
                        

The Responsibility of checking if the Parameters are provided or not falls on the function itself. There are two ways you can handle it.

One way is to check the value of each parameter and if it is undefined, then raise an error.

Another way is to supply a default value if the parameter is undefined. For our example. we can use 0 as the default value. The code checks each parameter and assigned 0 if undefined.

                            
function addNum(a, b) {
    if (a==undefined) a=0;
    if (b==undefined) b=0;
    return a + b ;
}
 
 
console.log(addNum());              //1
console.log(addNum(1));             //2
console.log(addNum(1,2));           //3
 
                            
                        
                            
                        

Instead of checking each parameter, we can make use of the default parameter

Using Default Parameters

The code below assigns 0 to both a & b parameters. The JavaScript checks each argument and if it is undefined then executes the assignment operation.

                            
function addNum(a=0, b=0) {
    return a + b ;
}
 
 
console.log(addNum());              //1
console.log(addNum(1));             //2
console.log(addNum(1,2));           //3
 
 
                            
                        
                            
                        

You can set any value as the Default Value.

                            

function addNum(a=1, b=1) {
    return a + b ;
}
 
console.log(addNum());              //2
console.log(addNum(1));             //3
console.log(addNum(1,2));           //3
 
 
 
                            
                        
                            
                        

Using Expressions as Default Values

You can use also use any expression as a default value. In the example below b takes an expression.

                            
x=1
y=2
 
function addNum(a=x, b=x+y) {
    return a + b ;
}
 
console.log(addNum());               //4
console.log(addNum(1));             //4
console.log(addNum(1,2));           //3
 
 
 
                            
                        
                            
                        

Evaluated at call time

The JavaScript evaluates the default values when we call the function.

In the following example, the a is 1 and b becomes 3 when we call addNum for the first time. We change the value of x & y and when we call the addNum again it will evaluate default values again. Hence a is 5 and b becomes 10.

                            
function addNum(a=x, b=x+y) {
    return a + b ;
}
 
x=1
y=2
console.log(addNum());              //4  (a=1 & b=3)
 
x=5
y=5
console.log(addNum());              //15   (a=5 & b=10)
 
 
 
                            
                        
                            
                        

Using earlier Parameters

You can also make use of earlier parameters in the default value expressions.

In the code below, b uses a in its expression.

                            
function addNum(a=1, b=a+1) {
    return a + b ;
}
 
console.log(addNum());            //3  (a=1 , b=2)
console.log(addNum(3));           //7  (a=3 , b=4)
                                 
                        

But the other way is not possible. The following example results in an error.

This is because JavaScript evaluates the Parameters from left to the right. The expression a=b+1 evaluates first and at that time b is not yet ready. Hence the error.

                             
function addNum(a=b+1, b=1) {
    return a + b ;
}
 
console.log(addNum());            
//Uncaught ReferenceError: Cannot access 'b' before initialization
   
                                 
                        

Passing undefined & null

You can not pass undefined if we use default values. Because, If the value is undefined then JavaScript assigns the default value. No such issue with the null

     
function addNum(a=1) {
    console.log(a)
}
 
addNum()           //1
addNum(undefined)  //1          //gets the default value.
addNum(null)       //null       //No issue with null     
                                    
                                

Hence if you want to pass an undefined value, then do not use default values

Default Parameters can appear anywhere

The default Parameters can appear anywhere in the parameter list.

In the following example, the first two parameters have default values. But the third parameter c does not have one. Here if we want to pass a value to the parameter c, then we need to explicitly pass undefined to a & b.

     
function addNum(a=1, b=2, c) {
    return a + b +c  ;
}
 
console.log(addNum());                  //NaN  (a=1 , b=2, c=undefined)
console.log(addNum(3));                //NaN  (a=3 , b=2, c=undefined)
console.log(addNum(3,6));              //NaN  (a=3 , b=6, c=undefined)
console.log(addNum(3,6,10));           //19  (a=3 , b=6, c=10)
console.log(addNum(undefined,undefined,10));   //13  (a=3 , b=6, c=10)
                                    
                                

Function as default Value

You can also use another function as the Default Value.

The showNumber uses another function getNumber to assign a default value to the parameter a

     

    function showNumber(a=getNumber()) {
    console.log(a)
}
 
function getNumber() {
    return 10;
}
 
showNumber()   //10
showNumber(5)  //5