Learn ES6 (ECMAScript 2015) Part 3 - Default Values for Function Parameters

Default arguments in ES6 allow you to assign some defaults to arguments. If I run this right now I’ll get undefined, undefined because nothing was passed in for greeting or names, so when they get logged out they're both undefined.

function greet(greeting, name){
console.log(greeting + ", " + name);
}
greet();

If I want it’s name to at least default to John, if I don't pass anything in, I then get undefined, John. I didn't pass anything to greeting, but I said the name should at least be John so it logs out the name as John.

If I pass in "Hello", I will get Hello, John. Hello comes through the greeting, greeting becomes "Hello" and the name still defaults to John.

function greet(greeting, name = "John"){
console.log(greeting + ", " + name);
}
greet("Hello");

If I say Hello, Bill, the default will be overridden and I'll get Bill instead of John, because the default was John, but I said explicitly to say Bill.

function greet(greeting, name = "John"){
console.log(greeting + ", " + name);
}
greet("Hello", "Bill");

Where this gets a little bit crazier is when you assign a default function to one of the arguments. Right now, complete is undefined, so it will say undefined is not a function when I try to invoke it.

function receive(complete){
complete();
}
receive();

But, if I pass in a function and say log complete, and I run this, it will logged complete out, because it invokes it when it's passed in.

function receive(complete){
complete();
}
receive(function(){
console.log("complete");
});

But, I can take that function and assign it as the default function and then I’ll rerun it and I still get "complete".

function receive(complete = function(){
console.log("complete");
}){
complete();
}
receive();

We can make this a little bit shorter using the arrow syntax. I can assign a default function, all within that same line, run it again, and I still get "complete".

function receive(complete = () => console.log("complete")){
complete();
}