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
Christian Cargill
8,065 PointsCan someone explain functions within functions to me?
Hi everyone,
So, I've been reading Eloquent JavaScript and I took JS basics here on TTH, but I'm still confused about why you would wrap a function inside of another function. From what I understand, functions are a way of organizing blocks of code that you can reference as a variable within your global scope (or within another function)..
But, I get lost when I see instructors putting functions inside of functions. I think I begin to get confused when JS starts to go layers deep within itself. If you wrote one function and then called it, I would understand that. But once you begin to add other functions (event listeners, handlers - are these functions?) I have a difficult time processing what's going on.
So, in layman terms, can someone help explain this to me? It's really the "layers" deep thing with code that overwhelms my brain :P
Edit: I read this blog post: http://taha-sh.com/blog/understanding-closures-in-javascript
And, I guess the take away is... encapsulation?
Thanks everyone!
1 Answer
Robert Walker
17,146 PointsI got really confused starting out and to be honest there are times when i still get confused but to really put this into simple terms:
Look at it like this, please remember this is just me trying to explain it the way I got it in the end.
Take an object like a car, once you get inside a car you have a number things you can do, put your seat belt on, start the car, adjust the mirror etc
So if you think of getting into the car as the first function, inside that first function you have another 10 functions that all enable you to do a different thing, put your seat belt on, start the car and adjust the mirror each action you can take once you get in the car cant be done unless you actually get in the car first.
function getInTheCar(){
function putSeatBeltOn(){
}
function startCar(){
}
}
If you dont get in the car just like in real life you cant put your seat belt on. This is by no means the best way to explain it but it worked for me when trying to grasp functions inside other functions.