Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Function default parameter values

I am super confused about the rules on default parameter values in JavaScript.

Say I have a function:

function foo(a=1, b=2, c=3) {
    return a + b + c;
}

When I run foo(a=2, b=3, c=4) in different places I got different results.

  • In the command line node.js (v8.9.1) and Safari console, this is perfectly fine.
  • In Atom, with script package (which also uses node to run scripts), I got a reference error, saying that a is not defined.

Is this just an Atom-specific issue? And what is the best practice to set and use default parameter values?

1 Answer

Steven Parker
Steven Parker
231,269 Points

The equal signs in the function definition establish default values, but using them in the function call does something entirely different. This would create or reassign global variables, which is probably not what you are intending. It can also cause an error if it is being run in "strict" mode.

So instead of "foo(a=2, b=3, c=4)", you should just call it with "foo(2, 3, 4)". The defaults only take effect when you leave off one or more arguments (such as "foo(5, 6)" or "foo()").

Thanks for replying. What if I want to skip a parameter? Say I want to seta=5and c=6 while using the default value of b?

Steven Parker
Steven Parker
231,269 Points

You'd need to pass the parameters in a different way. For example, using an object:

function foo({a=1, b=2, c=3}={}) {
    return a + b + c;
}
console.log( foo({a:5, c:6}) );  // shows 13

Happy coding!

Fantastic. Thank you!