Default function arguments in ES6

JavaScript has been extended with default function arguments in ES6. They work much like in other languages such as C#.

Here’s an example with a two arguments, one compulsory, one default:

function greeting(name, period = 'morning') {
  console.log(`Good ${period}, ${name}`)
}

Here’s how to call the function with the compulsory argument only:

greeting('John')

Here’s the output in the console window:

Good morning, John

…i.e. the parameter “period” was assigned the default value “morning” in the absence of a concrete value. In the above case “period” is undefined and this undefined value is overridden by the default value.

We can easily override the default value:

greeting('John', 'afternoon')

…which produces the following output:

Good afternoon, John

It’s a good idea to put the default arguments to the end of the argument list. Consider the following version of the greeting function:

function greeting(name, period = 'morning', age) {
  console.log(`Good ${period}, ${name}`)
  console.log(`Your age is ${age}`)
}

Say we want to go with the default value and only provide the name and age:

greeting('John', 20)

This results in the following output:

Good 20, John
Your age is undefined

Putting the default variable to the end of the parameter list will solve the problem:

function greeting(name, age, period = 'morning') {
  console.log(`Good ${period}, ${name}`)
  console.log(`Your age is ${age}`)
}

Should you ever face the situation where the default argument is provided somewhere in the middle of the list of parameters you can provide an ‘undefined’ to let the default value win:

greeting('John', undefined, 20)

View all posts related to JavaScript here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.