Close

JavaScript - Default Parameters

[Updated: Sep 22, 2018, Created: Jul 16, 2018]

ES6 (ECMAScript 2015) introduced a way to declare default values for the function parameters. Now we can inline default parameters values using = operator.

Examples

function getArea(w, h = 1) {
    return w * h;
}
console.log(getArea(3));
console.log(getArea(3, 2));

Passing null or undefined:

function print(x = 1) {
    console.log(x);
}
print();
print(null);
print(undefined);

Using arrays as default parameter

function print(x = [1, 2, 3]) {
    console.log(x);
}
print();
print(5)
print([5, 6]);

Backward Referencing

Default Parameters can use other parameters which have already been defined:

function getArea(w, h = w) {
    return w * h;
}
console.log(getArea(5));
function getArea(w, h = w * 2) {
    return w * h;
}
console.log(getArea(5));
function print(str, otherStr = `The ${str} with other`) {
    console.log(str);
    console.log(otherStr);
}
print("test");

In the last example we used ES6 template literal feature.

Function call

function getArea(w, h = getH()) {
    return w * h;
}

function getH() {
    return 3;
}
console.log(getArea(5));

Ordering default/non-default parameters

Default parameters can be declared in any order. In case where default params come before non-default params, we can pass the undefined to use default values for them.

function test(x = 1, y) {
    console.log(`x = ${x}, y = ${y}`);
}
test(undefined, 3);
test(5, 3);

See Also