0

This is more of a curiosity thing than a code not working thing.

It would seem that when using Async Functions in JS, mutating passed in variables works as one would expect, while reassigning them does not.

Here are two examples:

Arrays:

async function asyncResponse(x) {
  return x
}

const anAsyncFunctionToUpdateArray = async(arrayToUpdate) => {
  const res = await asyncResponse(3)
  arrayToUpdate = arrayToUpdate.concat(res)
}
const anAsyncFunctionToUpdateArray1 = async(arrayToUpdate) => {
    const res = await asyncResponse(1)
    arrayToUpdate.push(res)
  }
  (async() => {
    let anArrayToUpdate = []
    anArrayToUpdate.push(2)
    await anAsyncFunctionToUpdateArray(anArrayToUpdate)
    await anAsyncFunctionToUpdateArray1(anArrayToUpdate)
    console.log(anArrayToUpdate)
    //expecting [2,3,1]
    //but get [2, 1]
  })()

Objects:

async function asyncResponse(x) {
  return x
}

const anAsyncFunctionToUpdateObj = async(ObjToUpdate) => {
  const res = await asyncResponse(3)
  ObjToUpdate = {
    ...ObjToUpdate,
    'baz': res
  }
}
const anAsyncFunctionToUpdateObj1 = async(ObjToUpdate) => {
    const res = await asyncResponse(1)
    ObjToUpdate.fun = res
  }
  (async() => {
    let anObjToUpdate = {}
    anObjToUpdate.foo = 'bar'
    await anAsyncFunctionToUpdateObj(anObjToUpdate)
    await anAsyncFunctionToUpdateObj1(anObjToUpdate)
    console.log(anObjToUpdate)
    //expecting { foo: 'bar', baz: 3, fun: 1}
    //but get { foo: 'bar', fun: 1}
  })()

I tried googling for it, but I couldn't find anything quite explaining why reassignments don't work, but mutations do.

If anyone has an idea, or even a "duplicate: here's an old post about it" response, I'd love to hear from you.

Thanks!

  • 1
    This has nothing to do with `async`. That's how (local) variables work in JS. – Thomas Mar 16 '21 at 00:36
  • @jered, absolutely. Thank you so much. I got so wrapped up in the functions being async I did not check if the functions would operate the same way were they not. Completely makes sense now. – Murray Gudesblat Mar 16 '21 at 00:50

1 Answers1

0

Ah, as mentioned by others in the comments on my original post:

This has nothing to do with the functions being async, and everything to do with references vs values.

As answered here: Does Javascript pass by reference

Because the variables being passed into the functions are not primitive, what is passed in is an object/arrays reference. So when we mutate that variable, the mutation persists. However, if we reassign a new reference to the localized variable, it does not.

Thank you commenters for your help.