setTimeout and value capturing

  closures, javascript, scope, settimeout

I am trying to wrap my head around the reason for the following behavior:

First example:

let x = 3;

setTimeout(console.log, 1000, x); // 3

x = 4;

console.log(x) // 4

Second example:

let x = 3;

setTimeout(() => {
   console.log(x) // 4
 }, 1000); 

x = 4;

console.log(x) // 4

Could anyone please explain?

Source: Ask Javascript Questions

LEAVE A COMMENT