How do javascript async callbacks reference arguments that are passed in?

With the code below, I’d expect that the timeout prints out a value of 4, since the reassignment of the variable a occurs before the timeout is triggered. However, 2 is printed – I’m wondering why that is the case. Does the queue for async functions make a copy of the input variables?

const asyncFn = (value) => {
    setTimeout(() => {
        console.log(value)
    }, 500) 
}

let a = 2
asyncFn(a)
a = 4

136 thoughts on “How do javascript async callbacks reference arguments that are passed in?”

Leave a Comment