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 JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Introducing Loops, Arrays and Objects

Randolph Judy
PLUS
Randolph Judy
Courses Plus Student 28,198 Points

Optional parameters in JavaScript Functions

Is there a keyword that can be used to define optional arguments when declaring functions in JavaScript ? I have worked with other languages where this is possible.

2 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

HI Randolph Judy

No, that feature isn't currently in JavaScript. However, it is proposed in ECMAScript 6 (the next version of JavaScript): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

However, you can sort of fake it like this:

function myFunction(a, b, c) {
   a = a || 'default a';
   b = b || 'default b';
   c = c || 'default c';
}

In this example, if you call this function without passing any parameters, then a, b and c get set to a default value. This won't work, however, if you are expecting 0 as a possible value, because JavaScript treats the number 0 as a false value. In that case you can do something like this:

function myFunction(a, b, c) {
   if (a === undefined) {
       a = 'default a';
   };
   if (b === undefined) {
       b = 'default b';
   };
   if (c === undefined) {
       c = 'default c';
   };
}

Also keep in mind that with this method, you can't skip 'a', but still pass 'b' and 'c' to the function.

D P
D P
3,503 Points

You could also combine your two approaches by using the ternary operator:

function myFunction(a, b, c) {
   a = a !== undefined ? a : 'default a';
   b = b !== undefined ? b : 'default b';
   c = c !== undefined ? c : 'default c';
}

This isn't "better" but I like it because it's visually apparent that you're setting defaults and you don't have to worry about the scenario where you might have a 0 passed as an argument.

technically all params are optional when calling the function :) you can even call it with more params then you defined as well