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 Uses for Closures

Dee K
Dee K
17,815 Points

Why do we need closure for the function we use inside the for loop?

I am curious as to why this function wouldn't work when we reference it in the for loop.

function createHandler(name) {
    console.log(name);
  }

Why is it that we need closure and need to use this function instead?

function createHandler(name) {
  return function() {
     console.log(name);
  }
}

Any explanation would be greatly appreciated!

1 Answer

Steven Parker
Steven Parker
231,248 Points

Those functions do different things. The first one just calls console.log, almost as if it were a replacement for it.

But the second one just defines a function that will call it when invoked. And with a specific argument.

So they would be used in different ways.

// the first one:
createHandler("example one");  // this logs the words "example one" on the console

// the second one:
var myfunc = createHandler("example two");  // nothing happens ... yet
myfunc();                                   // but now this logs "example two" on the console