So, I’ve been trying to tackle the concept of closures and have been watching multiple people explain it. From my understanding it’s having access to the scope of a parent function after the parent function has already run and closed.
I’m somewhat understanding them and what they are, but I don’t understand why you would actually use them.
everything I’ve seen so far explains pretty well what they are, but no one seems to explain why you would use them.
I get confused on why someone wouldn’t do something like this.
let globalvariable = 'global'
function outerFunction() {
let outerVariable = 'outer'
function innerFunction() {
let innerVariable = 'inner'
console.log(`${globalvariable} ${outerVariable} ${innerVariable}`)
}
innerFunction()
}
outerFunction()
over something like this.
let globalvariable = 'global'
function outerFunction() {
let outerVariable = 'outer'
function innerFunction() {
let innerVariable = 'inner'
console.log(`${globalvariable} ${outerVariable} ${innerVariable}`)
}
return innerFunction
}
let innerFunct = outerFunction()
innerFunct()
In this example, we want to be able to create multiple counters that keep track of how many times they have been called. The main function counter returns the inner function counterInfo. It is really counterInfo that gets called after initializing a variable with a call to counter. The count variable is accessible to the counterInfo function, so it can return its value when the intialized counter gets called.
In your example above, you are calling counter twice with number1 as the argument and 3 times with number2 as the argument. But since, counter just calls counterInfo each time, count will always be 1 as each time counter is called, count starts at 0.
In my example, I assign the call of counter to two variables. Each time I call counter, a new count is set to 0 and since I return the counterInfo function instead of just calling it, I preserve the current count for variable where counter is called.
Yes, you seem to understand the difference better now.