Home TutorialsModern ES6 Syntax Default Function Parameters

Default Function Parameters

by TheScriptKiddie

Default Function Parameters

Default function parameters are useful if you want to make an argument to a function optional, and include a default fall-back value. To see the usefulness of this syntax, it will help to see how it was accomplished before ES6 default function parameters:

function sayHello(name) {
    if (typeof name === 'undefined') {
        name = 'World';
    }
    console.log(`Hello ${name}!`);
}

sayHello('James');
sayHello();

Basically, we had to write code to check whether the function parameter is undefined, and if so, set it to some default value. The new syntax is much simpler:

function sayHello(name = 'World') {
    console.log(`Hello ${name}!`);
}

You may also like

Leave a Comment