0

I was hoping that this code

let name = 'Sally'
setTimeout(() => console.log(name), 3000)
name = 'Pepe';

Would output Sally (because of the timeout handler declaration "capturing" the name), but it doesn't happen in the Console. Why is that? I know it is related to closures but it seems I didn't fully understand it, as this very same problem happens a lot to me in React but I wanted to simplify and couldn't.

JorgeeFG
  • 5,651
  • 12
  • 59
  • 92
  • There is only one binding for `name`, on the top level of wherever the code is being executed. When you do name = 'Pepe'`, you reassign what that one variable name points to. Then when `console.log(name)` is done later, it looks up the current value that the `name` binding points to, which is the new string. – CertainPerformance Nov 10 '20 at 02:32
  • @CertainPerformance I don't totally get you. Is it possible that you can modify the code to generate a stale property? – JorgeeFG Nov 10 '20 at 02:36
  • I guess if you saved the original string into a different variable first, then had the timeout callback examine that different variable? – CertainPerformance Nov 10 '20 at 02:39
  • It doesn't capture the name. Instead it captures the variable. Since the name changes it would print the current name instead of the past name. To capture the value itself you would need a function that executes now instead of in the future: `function x () {let y = name; return function () {console.log(y)}}; setTimeout(x(), 3000)` – slebetman Nov 10 '20 at 03:49

0 Answers0