...

/

Default Function Arguments

Default Function Arguments

In this lesson you will learn what are default function arguments and how to use them.

We'll cover the following...

Prior to ES6, setting default values to function arguments was not so easy. Let’s look at an example:

Press + to interact
function getLocation(city,country,continent){
if(typeof country === 'undefined'){
country = 'Italy'
}
if(typeof continent === 'undefined'){
continent = 'Europe'
}
console.log(continent,country,city)
}
getLocation('Milan')
// Europe Italy Milan
getLocation('Paris','France')
// Europe France Paris

As you can see, our function takes three arguments: a city, a country and a continent. In the function body we are checking if either country or continent are undefined and in that case, we are giving them a default value.

When calling getLocation('Milan') the second and third parameter (country and continent) are undefined and get replaced by the default values of our functions.

But what if we want our default value to be at the beginning and not at the end ...