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 trialMichael Nickey
Courses Plus Student 13,524 PointsDefault values for parameters
In this video you showed how to create a value inside the function to stop 'undefined' when a parameter is not used.
Can't we set a default value for the parameters when creating the function? Something like:
function addTheValues (a=0, b=0) {
return a + b;
}
2 Answers
Andrew Kiernan
26,892 PointsHi Mike!
I believe there is a way you can set default values in a function. You can set each variable to the parameter value and use the or operater ( || ) to set a default value. So like this (the function will add the values you pass in, and would default to returning 4, for a=2, b=2):
function addTheValues ( a, b ) {
var a = a || 2;
var b = b || 2;
return a + b
}
Michael Nickey
Courses Plus Student 13,524 PointsNot quite what I was looking for but it'll work.
In Python we have something like this where we can define the variables inline as we note then between the parenthesis.
>>> def F(a, b=[]):
... b.append(a)
... return b
Thanks though for the info.