The function counter can be a closure?
let count = 0;
function counter() {
return count +=1;
}
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
The function counter can be a closure?
let count = 0;
function counter() {
return count +=1;
}
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
The function counter can be a closure
Yes
closure is not only in nested function. The declaration of function in global scope is also a closure. According to MDN
A closure is the combination of a function and the lexical environment within which that function was declared
A closure is the combination of a function with references to its surrounding state (the lexical environment) combined together.
Every time you create a function you create a closure at function creation time
let count = 0;
function counter() {
return count +=1;
}
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Function counter doesn't define any variable count
still has access to the count because
count
has been defined in the scope in which the closure was created.Additionally closures are capable of not only reading, but also manipulating the variables of their lexical environment
which you are doing in your case.So precisely your function counter
solely is a not a closure ,
function counter +its lexical environment is a closure