mistrbrown
mistrbrown

Reputation: 1

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

Upvotes: 0

Views: 160

Answers (1)

Ramin
Ramin

Reputation: 71

This is a very interesting question. I think though for you to get a better grasp of the dynamic behind this you should try the following version:

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

const a = { value: 2 }
asyncFn(a)
a.value = 4

Your example was misleading because JS passes primitive values like numbers by value and not by reference on the other hand arrays and objects are passed by reference. As you can see when you use an object we actually get the changed value in the console log!

Upvotes: 1

Related Questions