Why use default parameters in JavaScript functions?

Why use default parameters in JavaScript functions?

JavaScript functions are first-class citizens. Learn how to set default function parameters with examples and explanations.

ยท

6 min read

Function in programming is a block of code that performs a specified task. You define them once and can call them(using a name in most cases) wherever you want to perform that task.

JavaScript is no different. In JavaScript, one of the popular ways to define(or declare) a function using the function keyword, a meaningful name, a pair of parenthesis, and followed by a pair of curly braces where you define the tasks/instructions.

function doSomething() {
    // Instrauction to do something.
}

Optionally, you can pass one more parameter to a function.

// Define a function add with two parameters
function add(x, y) {
    return x + y;
}

// Invoke/Call the function passing the actual values
add(2, 3); // It returns the number 5

Parameter vs Argument in JavaScript Function

Like other programming languages, JavaScript also has some terms and jargon for you to get confused. One of them is Parameter vs Argument.

  • Parameters: These are the variables we define when we declare a function.

  • Arguments: These are the values we pass to a function when we invoke/call the function.

The code snippet below demonstrates the difference with an example.

parameter vs arguments

Did you know I share knowledge and tips like these on X and LinkedIn? Connect with me if you do not want to miss them.

How to set default function parameters in JavaScript?

The default function parameters allow you to initialize a parameter with a default value. You can use the equal sign(=) and the value to initialize a parameter while declaring the function.

// Here the message paramater is a `default function parameter`
// as we initialize it with a default value.
function greetMe(name, message="Hello") {
    return `${message} ${name};`
}

// When we do not pass a value for the message,
// The default value is used.
greetMe("tapaScript"); // Hello tapaScript

// When we pass a value for the message,
// The passed value override the defaule value.
greetMe("tapaScript", "Hola"); // Hola tapaScript

In the above code, the greetMe function takes two parameters name and message. The message parameter is a default function paramater as we initialize it with a default value.

When we do not pass a value for the message, the default value is used. But, when a value is passed, the passed value is used by overriding the default value.

Note that if you pass an undefined for the default parameter, it will take the default value.

console.log(greetMe("tapaScript", undefined)); // Hello tapaScript

Use case 1: Safeguard function's return value

Consider a situation where you perform some arithmetic operation in a function, like taking two numbers as parameters and returning the double of their addition.

// A functiont to sum up two numbers
// and return the double of it.
function calc(a, b) {
    return (2 * (a + b));
}

When you pass arguments for both parameters, the function outputs the desired result.

calc(2,3); // Output is 10

However, when you miss out on one (say, the second one), the output may not be the desired one.

calc(2);

In this case, the output is,

NaN # That is Not a Number

It is because we were trying to add undefined to a number. You could fix it by adding checks within the function. If the parameter b is undefined, handle it in some way, may consider the value of b as 0.

if(!b) {
 b = 0;
}

That's an unnecessary condition when you can do the same with the default function parameter. You can set the initial value of b with 0.

function calc(a, b=0) {
    return (2 * (a + b));
}

Great! Now, if you miss out on passing the value for b, the function considers the value of it as 0 , and the output is a much more predictable one.

calc(2); // Output is 4

You can do the same for both parameters.

function calc(a=0, b=0) {
    return (2 * (a + b));
}

The output when someone calls the calc() function without passing any arguments.

calc(); // Output is 0. Better than a NaN

Use case 2: Construct default parameter from existing parameters

You can construct the value of the default function parameter from the existing parameter's value.

function sayGood(name, gender, message=`${name} is a good ${gender}`) {
    return message;
}

In the example code above, we have initialized the message parameter with a value which is constructed by the other two former parameters name and gender. So when you invoke the sayGood function with the value of name and gender, it will return a well-constructed message value accordingly.

sayGood('Alex', 'Boy'); // Alex is a good Boy
sayGood('Emilie', 'Girl'); // Emilie is a good Girl

Use case 3: Setting an empty array as the default value for the destructured parameter

You can set an empty array or object as the default value for the destructured function parameters.

function emp([dept = 'Manager', salary = 2000] = []) {
  return `${dept} gets ${salary}`;
}

The method emp sets up an empty array as the default value for the destructured parameters, dept and salary. So, when you pass an empty array to the function, it will take the default values for the dept and salary.

emp([]); // Manager gets 2000

You can override default values by passing the new value as an array element.

emp(['Employee']); // Employee gets 2000

Another example,

emp(['Employee', 1500]); // Employee gets 1500

A few more things to note about the default parameters

JavaScript's default function parameters are amazing, isn't it? Let's talk about a few more important aspects you need to keep in mind. These are important for the interviews as well ๐Ÿฅน.

Arguments for the default parameters get evaluated at the call time

Consider this code snippet,

function tryThis(value, arr = []) {
  arr.push(value);
  return arr;
}

Now, let's call the tryThis function with an argument:

tryThis('๐Ÿ˜Š');

By now, you can guess the output. Yes, it will be,

['๐Ÿ˜Š']

Fair enough. But what if we invoke the tryThis function again(the second time) with an argument,

tryThis('๐Ÿฅน');

What will be the output of the second time call?

  1. ['๐Ÿ˜Š']

  2. ['๐Ÿ˜Š', '๐Ÿฅน']

  3. ['๐Ÿฅน']

The answer is #3, ['๐Ÿฅน'].

It is because every time we invoke the tryThis function, a new instance of the array arr will be created. Thus, when we call the function a second time, the previous instance of arr(with '๐Ÿ˜Š') has been destroyed, and a new one has been created with the argument('๐Ÿฅน') we passed.

The default parameter value and the function's scope

You can not use anything from the function body as an initializer for the default parameter.

function fx(t = task()) {
    function task() {
        // Do Something...
    }
}

In the above code snippet, we are trying to use the task() function as an initializer for the parameter t. This is not allowed. We will get a ReferenceError.

fx(); // ReferenceError: task() is not defined

Hold on, here is something more for you...

Do you want to learn more about JavaScript functions from a well-structured crash course? Yes, it is available for FREE. Check it out.

Don't forget to SUBSCRIBE to tapaScript for the future content ๐Ÿ˜Š


Before We End...

That's all. Thanks for reading it. I hope it was insightful. If you liked the tutorial, please post likes and share it in your circles.

Let's connect. I share web development, content creation, Open Source, and career tips on these platforms.

Did you find this article valuable?

Support Tapas Adhikary by becoming a sponsor. Any amount is appreciated!