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

Vladimir Plokhotniuk
Vladimir Plokhotniuk
5,464 Points

I cannot understand fully

Why then dont working option like this:

var buttons = document.getElementsByTagName('button');

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

for(var i = 0; i < buttons.length; i += 1) {
    var button = buttons[i];
    var buttonName = button.innerHTML;
    button.addEventListener('click', createHandler(buttonName));
}

2 Answers

Aakash Srivastava
Aakash Srivastava
5,415 Points

Hey Vladimir Plokhotniuk ,
Functions are what are called "first class" citizens. You can pass functions to other functions, return functions from functions and even use functions to build other functions . So , he is creating a function with console.log statement and then returning that function.
Let's come to the second part , i,e why you can't return a console.log directly :

console.log(name) is a statement which gets executed not a value which can be returned. console.log will display the parameter passed to the log method in the console window. Use this method to display a string or variable in the console window.
When using the return statement, the function will stop executing, and return the specified value.
You can't combine both the statements.
Hope this helped.

odzer
odzer
20,483 Points

What you posted, without the closure, has no practical difference from the code in the beginning of the video, which was leading to all buttons having the same name. The only difference is that it is declared separately as a named function.

You need the closure so that every time the button name is passed into the outer function, the inner function keeps the name that it is passed during that call of the outer function. Without the closure, the function simply gets the name from the global scope, so it is always the same.