Default Parameters in ES6
Default parameters have been a great addition to ES6, and they are fairly easy to understand with this quick walk through.
So, we start off with some simple code as below. Here, we are passing no arguments, no parameters, my entire statement is in the console log.
const myFaveAnime = () => {
console.log("Gintama is my favourite anime");
}myFaveAnime();
My favourite anime tends to change all the time, so lets fix this using use parameters and arguments. Note that (anime) is the parameter and “Fairy Tail” is the argument. These two are often used interchangeably when they are in-fact, different. You pass in arguments when calling the function.
const myFaveAnime = (anime) => {
console.log(`${anime} is my favourite anime`);
}myFaveAnime("Fairy Tail");
But what happens if I forget to pass in argument? Undefined.
const myFaveAnime = (anime) => {
console.log(`${anime} is my favourite anime`);
}myFaveAnime();
I’m pretty sure there isn’t an anime called undefined. We prevent this from happening through the use of default parameters, which will act as a fall-back or safety net answer for when no argument is passed.
const myFaveAnime = (anime = "Vinland Saga") => {
console.log(`${anime} is my favourite anime`);
}myFaveAnime();
Now, “Vinland Saga” has been set as my default. To override this, we just pass in an argument as normal!
const myFaveAnime = (anime = "Vinland Saga") => {
console.log(`${anime} is my favourite anime`);
}myFaveAnime("Black Clover");
Happy coding!