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

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
firmfiasco
  • 121
  • 2
  • 2
  • 9

1 Answers1

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...

TazGR
  • 73
  • 7