0

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
4
  • 1
    Keyword: closure. Commented Jan 30, 2021 at 19:06
  • 1
    Parameters are passed by value, not reference. The parameter has the value 2 because a copy of the source value was made when the function was called. Commented Jan 30, 2021 at 19:06
  • 1
    Nothing to do with async. JS is simply a pass-by-value language, not pass-by-reference. Commented Jan 30, 2021 at 19:06
  • 1
    @mistrbrown - don't know if you missed it or not, but jonrsharpe's comment about the closure is more important than pass by value. If you remove the function and call setTimeout() directly, you will see the result you expected. Run this in the console to see the difference: let a = 2; setTimeout(()=>{console.log(a)}, 500); a = 4; Commented Jan 30, 2021 at 19:41

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.