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
Cameron Raw
15,473 PointsPassing arguments/parameters to inner functions?
Hi,
I'm afraid I haven't got an example but it's a pretty generic question. Is there any information on how arguments or parameters are passed into other functions nested inside?
The way I understand functions arguments are like this:
function newFunc(arg1, arg2){
var example = arg1;
var example2 = arg2;
}
This seems very clear to me, but when there are nested functions within functions, arguments seem to get passed around I don't understand.
Thanks
1 Answer
Jesus Mendoza
23,289 PointsFunctions have access to all variables from the outside.
var x = 1;
function newFunction(arg1, arg2) {
/* This is a representation of whats happening "behind scenes" when you pass an argument to a function. It creates a new variable and assign it the value from the arguments object (Which all functions have). */
var arg1 = arguments[0];
var arg2 = arguments[1];
function nestedFunction(arg3, arg4) {
var arg3 = arguments[0];
var arg4 = arguments[1];
}
}
- nestedFunction will have access to all variables created in the parent function and in the global scope.
- newFunction will have access to its own variables and the variables in the global scope.
- the global scope will have access only to variables in the global scope.
When you pass arguments is like if you were cretating new variables inside the function you are passing variables to and since nested functions have access to its parents variables then it will have access to its parents arguments.
Cameron Raw
15,473 PointsCameron Raw
15,473 PointsThanks for the quick reply. So, if you were to call newFunction, would you be able to pass arguments into the parenthesis to be used in nestedFunction? I Can arguments be passed in this way?
newFunction(arg3, arg4);