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:


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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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

%d bloggers like this: