0

I'm currently looking at the 2nd solution of the 2nd question on this page,

https://www.sitepoint.com/5-javascript-interview-exercises/

I'm stuck why you need a closure.

function handlerWrapper(i) {
   return function() {
      console.log('You clicked element #' + i);
   }
}

Why do I need to the return function. When I try

function handlerWrapper(i) {

     console.log('You clicked element #' + i);

}

It doesnt work. What exactly does including the

console.log('You clicked element #' + i);

within the return function do? Why does it work and why do I need to do it within the return function?

Thank you ahead of time

1 Answer 1

1

Well it's simple, lets say this:

function printToConsole(callback) {
    workOrSomething();
    callback();
}

function handlerWrapper(i) {
     console.log('You clicked element #' + i);
}

//This doesn't know what i you want.
printToConsole(handleWrapper); -> You clicked element #undefined

function handlerWrapper(i) {
    return function() {
        console.log('You clicked element #' + i);
    }
}

//This does
printToConsole(handleWrapper(3)); -> You clicked element #3

I hope you got the idea...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.