Default Parameters in JavaScript ES6

Made by Marvin Drude

Default Parameters in JavaScript ES6

If you ever programmed in other languages than JavaScript, you are might be familiar with the concept of default parameter values if given parameter is not passed through. This concept exists in C# for example.

We all know how tiring it is to do the checks for parameters in ES5.

var log = function(file, line, message, someBool) {

    file = file || "default.js";
    line = line || 20;
    message = message || "No message";

    someBool = (typeof someBool !== "undefined") ? someBool : true;

    //function

}

In this example, the log function has 4 optional parameters which we have to check on. If a parameter is not provided on call, it gets assigned a default value. Without these kind of safeguards in place, any uninitiated parameters would have a value of undefined.

Our Savior in ES6

If you are lucky and your environment allows it to use ES6 features like Node.js or Apps, you will be happy to hear that you can now easily declare the default values of optional parameters.

var log = function(
    file = "default.js", 
    line = 20, 
    message = "No message",
    someBool = true) {

    // function

}

This allows us to write much easier to maintain code which at the same time is easier to read. ES6 also allows you to have the first parameter as optional, even though you have mandatory parameters following:

var test = function(file = "test.js", message) {

    console.log(file, message);

}

But important to know is that you would need to pass undefined as first parameter if you wanted to have the default value in place.

test(undefined, "Hello") // logs test.js, "Hello"

At the current date null doesn’t work like undefined. If you would replace undefined by null it would print null, “Hello”.

Dynamic Default Values

The default value is not limited to constant values like numbers or strings. It can actually calculate the default value on the spot.

var getDef = function(y) { 
    return y * 2;
}

var test = function(x, r = getDef(x)) {
    console.log(r);
}

test(20); // logs 40

The code above logs 40 because nothing is passed as r parameter when we call function test and therefore the default value for parameter r is calculated using other parameters.