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

Closures in Javascript

Hello, I'm trying to understand Closures in Javascript. I'm using another online resource tool and it does an absolutely horrible job of explaining. What are the best resources here?

Thanks, Fareez

2 Answers

From my understanding closures are a private anonymous function.

You set it up like this:

<code> (function () { //code })(); </code>

The code will be run immediately and will only be run once. You cannot reference any of the variables or code in the function. Closures are great when you want to initialize variables / run some code only once.

Heres an example at treehouse. Its starts around 13:30

http://teamtreehouse.com/library/javascript-foundations/functions/anonymous-functions