ES6 Tutorial: A Quick Introduction to Default Parameters in JavaScript6 min read

JavaScript ES6 comes and provides us a number of useful features, the default parameter is one of them. In this article, we will discover what default parameters are, how and when to use them.

Default Parameters Definition

Simply put, default function parameters allow you to set the default values for the parameters in case no value or undefined is passed. The syntax for default function parameters in JavaScript is as follow:

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

For example:

function greeting(x = "Human") {
    console.log("Hello " + x);
}
greeting(); // Hello Human
greeting("World"); // Hello World
greeting(""); // Hello 

In the first function call, because we haven’t passed any value to this function thus the value for x is undefined and the default value for this parameter x will be used. As a result, it gives us the output Hello Human. In the second call, because we have provided a value World as an argument, then the default value for the parameter x will never be involved, leads us the result Hello World. In the third case, we also have passed a value to this function, which is an empty string, then Hello will be displayed in the console.

Arguments vs Parameters

You can see the words arguments and parameters quite a lot and you might think they could be used interchangeably. However, by definition, parameters are what we designate in the function declaration, whereas the arguments are what we passed into the functions. For example we have a simple function:

function add(a, b) {
    return a + b;
}
add(5, 6);

a and b in this case are the parameters, whereas 5 and 6 are the arguments.

Back was the time when ES6 hadn’t come out, if you want to define a function with the same characteristics as above, here is the equivalent code, but a little more verbose:

function greeting2(x) {
    if (typeof x == undefined) {
        console.log("Hello " + "Human");
    } else {
        console.log("Hello " + x);
    }
    // x = x || "Human"; this is aslo OK.
}
greeting2(); // Hello Human
greeting2("World"); // Hello World
greeting2(""); // Hello

Dive more in default parameters examples

Passing undefined vs. other falsy values

The default value for parameters only involved when we pass an undefined value to the functions, hence, any value other than undefined (including all falsy values) if we pass in will cause not to involve default parameters, for example:

function foo(x = "A") {
    console.log(x);
}
foo(); // because x is undefined, then A is used
foo(undefined); // same as the case above
foo(""); // empty string is passed as the value of x
foo(null); // null is not undefined, then it will be display
foo(false); // false is not undefined
foo("NaN"); // NaN is not undefined
/*
Output:
A
A

null
false
NaN
*/

Using functions as default parameters

In JavaScript, functions are first-class objects, and they can be treated as any other variables. This is the reason why we can use a function as a default value for a parameter too!

let luckyNumber = () => 7;
let getLuckyNumber = (luckNum = luckyNumber()) => {
    console.log("The lucky number is: " + luckNum);
}
getLuckyNumber(); // The lucky number is: 7
getLuckyNumber(8); // The lucky number is: 8

In the first function call, we didn’t pass any value to this function, the luckyNumber function which returns value of 7 will be used as the default value in this case. The next call is proceeded as normal.

Also read:

We can use this feature to make arguments are mandatory. If when calling a function and we forget to pass any argument, then an error will be occur:

let argumentRequired = function() {
    throw new Error("The argument is required");
}

function areaOfRect(breadth = argumentRequired(), height = argumentRequired()) {
    return breadth * height;
}

areaOfRect(); // error
areaOfRect(5, 10); // 50

We first called a function areaOfRect but didn’t pass any value, then the default values for both breadth and height will be set, which leads us to call function argumentRequired and this function produces errors.

Passing the undefined value

In this section, we will explore more examples to enhance and consolidate what we have learned. Let’s create a simple function to change the font of a paragraph:

<div id="newid">

</div>
<script>
        function customFont(text = "Default Text", fontName = "Arial", fontSize = "20px", fontColor = "blue", fontStyle = "italic") {
            let div = document.getElementById("newid");
            div.innerHTML += text;
            document.getElementById("newid").style.color = fontColor;
            document.getElementById("newid").style.font = fontStyle + " " + fontSize + " " + fontName;

        }
</script>

In this customFont function, what it does is to take a div element, i.e div id="newid"> </div>, add a new text and then styling this text. In case we don’t pass any argument to this function, the default values for those parameters will be utilized:

customFont();

Here is what we get after fire this function:

In case if we just want to set the values of fontSize, fontColor and fontStyle and leave text and fontName with the default values, we can call the function as the following:

customFont(undefined, undefined, "50px", "red", "bold italic");

And here is the output after calling this function:

Early parameters are available to later default parameters

You can assign a parameter as a default parameter value of other parameters. In other words, parameters defined earlier (to the left) are available to later default parameters:

function greet(greeting, name, messgage = greeting + " " + name) {
    console.log(greeting + " " + name + ". " + messgage);
}
greet("Hello", "You"); // Hello You. Hello You
greet("Hello", "You", "What's your name?"); // Hello You. What's your name?

Default parameter evaluation

Default parameters are evaluated at call time, which means a new object is created each time function called:

function push(value, arr = []) {
    arr.push(value);
    return arr;
}
push("One"); // ["One"]
push("Two"); // ["Two"] not ["One", "Two"]

The argument object

The number of argument objects is the actual number of arguments you pass into the function, consider the following example:


function argumentLength(a = 5, b = 6, c = 7) {
    console.log(arguments.length);
    return a + b + c;
}
argumentLength(); // 0 argument
argumentLength(20); // 1 argument
argumentLength(10, 20); // 2 arguments
argumentLength(10, 20, 30); // 3 arguments

A function inside another function as a default parameter

A function which declared inside a body of another function cannot referred outside its scope and be a default parameter value of the outer function, for example:

function foo(a = bar()) {
    function bar() {
        return "Functions defined inside function body cannot be a default parameter!"
    }
}
foo(); // Error!

The default function parameter is always executed first, the function declared in the body of function foo will be evaluated afterward. This gives us a ReferenceError.

Previous Article
Next Article
Every support is much appreciated ❤️

Buy Me a Coffee