I have this code:
for food in foods
Person.eat ->
console.log food
The problem here is that "food" will always be the last "food" in "foods". That is because I have the console.log in a callback function.
How can I preserve the value in the current iteration?
You need to close over the value of a loop if you want to geneate functions to run later. This what coffee provides the do
keyword for.
for food in foods
do (food) ->
Person.eat ->
console.log food
See this example: https://gist.github.com/c8329fdec424de9c57ca
This occurs because your loop body has a reference to the food
variable which changes values each time though the loop, and when you function if finds the closure the function was created in and finds that food variable set to the last value of the array. Using another function to in order to create a new scope solves the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With