below it is a loop with closure, i use “let” it will return 0,1,2,3,4 when i call the array function
function createFunctions() {
var functions = [];
for (let i = 0; i < 5; i++) { // * let scope will not be excuted first
functions.push(function () {
console.log(i);
});
}
return functions;
}
var funcs = createFunctions();
funcs[0](); // Outputs: 0
funcs[1](); // Outputs: 1
funcs[2](); // Outputs: 2
below it is almost same as above, i use “var” and it will return 5,5,5,5,5 when i call the array function
function createFunctions() {
var functions = [];
for (var i = 0; i < 5; i++) { // * var scope will be excuted first , call hoisting in javascript
functions.push(function () {
console.log(i);
});
}
return functions;
}
var funcs = createFunctions();
funcs[0](); // Outputs: 5
funcs[0](); // Output: 5
funcs[1](); // Outputs: 5
When I first time met it , I didn’t dive into deep to ask why, i just know it is hoist feature in Javascript ; but recently when i dealing with golang, i met this kind of closure too ;
func createFunctions() []func() {
var functions []func()
for i := 0; i < 5; i++ {
functions = append(functions, func() {
fmt.Println(i)
})
}
return functions
}
func main() {
funcs := createFunctions()
funcs[0]() // Outputs: 5
funcs[1]() // Outputs: 5
}
I met it again , it makes me feel vary uncomfortable ; above if you don’t copy the value , I will output 5,5,5,5,5
func block() []func() {
var functions []func()
for i := 0; i < 5; i++ {
value := i
functions = append(functions, func() {
fmt.Println(value)
})
}
return functions
}
func main() {
block := block()
block[0]() // Outputs: 0
block[1]() // Outputs: 1
}
Guess what , it will out put 1,2,3,4,5 …. ; I almost ask everyone I can ask , but they still can’t tell why , Can anyone help me ???
Block scope: Go also recognizes block scope. A block is any section of code surrounded by {}. If you declare a variable inside a block (like an if statement, for loop, or switch case), it’s only visible within that block.
In Go, there’s also another type of scope related to if, for, and switch constructs. For example, a variable declared in the initialization statement of an if or for clause is only visible until the end of the if or for clause.
Above it is I read from blog , but it does not make any sense ???