Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

    Default Values for Function Parameters in ES6

    John LindquistJohn Lindquist

    With ECMAscript 6 we get the luxury of default parameters for our functions.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Lukas: 00:00 default arguments in ES6 allow you to assign some defaults to these guys. If I run this right now you'll see I'll get "undefined, undefined" because nothing was passed in for "greeting" or "names", so when they get logged out they're both undefined.

    00:15 If I want his name to at least default to John, if I don't pass anything in, I can get "undefined" to "John". I didn't pass anything in here, but I said the name should at least be John so it logs out the name as John.

    00:29 If I pass in "Hello" here, and then run this, you can see I get "Hello John". "Hello" comes through the greeting, logged out here as "Hello" and the name still defaults to John, and then is logged out here.

    00:45 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.

    00:58 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.

    01:10 But, if I pass in a function and say "log complete", and I run this, you can see it logs complete out, because it invokes it when it's passed in.

    01:21 But, I can take this function, I'll cut it out of here and then assign that as the default function and then I'll rerun it and you'll see I still get complete.

    01:31 We can make this a little bit shorter using the arrow syntax that I've covered before. If I do that and then get rid of the braces and then bring everything up to the same line, you can see that I can assign a default function, all within that same line, run it again, and I still get complete.

    01:49 If you want to go completely crazy with arrow functions, which I don't recommend, you could go "let receive" and I'll assign it to an arrow function, delete these braces, pull everything up to the same line, and then just invoke it this way. It still runs and this just doesn't look like JavaScript.

    02:07 It's not a JavaScript you'd write, but it's very unfamiliar with the new syntax, with the arrow functions and the default assignments all working on the same line.