How To Set Default Parameter In JavaScript Function

How To Set Default Parameter In JavaScript Function

In this quick tutorial, you’ll learn how to set default parameter in JavaScript function. So, without wasting further time, let’s write some quick code to showcase how to set default parameter in JavaScript function and how its can you quite useful.

Getting Started

Let’s create a simple app.js file which will make some function calls to a helper file called helper.js.

/* app.js */

const helper = require('./helper')
helper.sayHello('Jay')

Here is the helper.js file :

/* helper.js */

module.exports = {
    sayHello : function(name){
        console.log(`Hello ${name}`);
    }
}

As you can see in the app.js file, sayHello method has been called with a value for paramter name. Try running the prorgam and it will print the passed in name to the terminal.

Set Default Parameter In JavaScript Function

Just in case no paramter is passed to the sayHello function, you can set a default value for it. Modify the helper method sayHello as shown:

/* helper.js */

module.exports = {
    sayHello : function(name = 'Dude'){
        console.log(`Hello ${name}`);
    }
}

Now if you try to call the helper method sayHello without a paramter it will use the default value for name parameter.

Set Default Object ParameterĀ In JavaScript Function

Similarly, you can set default value for a JavaScript object paramter passed to the function. Let’s create another function called sayGoodBye which accepts a JavaScript object as parameter.

/* helper.js */

module.exports = {
    sayHello : function(name = 'Dude'){
        console.log(`Hello ${name}`);
    },
    sayGoodBye : function({name = 'Dude',place = 'Kerala'} = {}){
        console.log(`Goodbye ${name}, it was nice having you at ${place}`)
    }
}

Now you can make a call to the sayGoodBye with parameter or without parameter. If without parameter it will pick up the default values else print the passed in values.

/* app.js */

const helper = require('./helper')
// Function call with no parameters passed.
helper.sayGoodBye();
// Function call with one object property passed
helper.sayGoodBye({name : 'Roy'})
// Function call with all parameter passed
helper.sayGoodBye({name : 'John', place : 'Delhi'})

Wrapping It Up

In this tutorial, you learnt how to set default parameter for JavaScript functions. I covered both scenarios when the parameter passed is an object and a variable. Do let us know you thoughts and suggestions in the comments below.

Leave a Reply

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