How to create a function with optional parameter in javascript


 

Hi, and welcome. 

I know you think this is a very easy issue right? You are supposed to know, don't worry we all have been there and we thought of the same thing. When you declare a function in JavaScript you provide the parameters that the function will need whenever its called. Maybe the parameter is used to to do something within the function maybe not. For the case of the situations where the function is called and no functions are defined there must be a way to overcome this scenario, which is what am going to show you

THE SCENERIO

//index.js

    //declaring a function

    const sayHi = (name=> {

        console.log('Hi ' + name);

    }

//call the function
    sayHi();

// the output is going to be
// Hi undefined


1. CHECK FOR THE PARAMETER BEFORE YOU USE IT

You can start by checking if the parameter was provided before you use it inside the function and then  customize an action you'd like to perform when the parameter was not provided. Just as seen below


    const sayHi = (name=> {
    
    if (name){
        console.log('Hi ' + name); 
    }else {
        console.log('Hi ' + 'you didn\'t provide a name');
    }
  
    }
//call the function

    sayHi();

// the output is going to be
// Hi you didn't provide a name


2. SETTING A DEFAULT LOCAL VARIABLE FOR THE PARAMETER

If there is a default value that can be used in your function body, or there are no any implication of setting the default to empty string in your function use below solution.


This article based on solution in stackoverflow click here for more solutions.

Thanks, 



Comments