'For loop value in Promise.then() inside

I have a question about promise.then() inside a for loop in node.js.

For a code like this:

const arrayObject = [
  {
    id: 1234,
    toto: 'abc'
  },
  {
    id: 5678,
    toto: 'def'
  },
  {
    id: 910,
    toto: 'ghi'
  },
]
const finalArray = []
let promiseArray = []
for (let singleObject of arrayObject) {
    promiseArray.push(
        Promise.function(...).then(res => {
            if (res === true) {
                finalArray.push(singleObject)
            }
        })
    )
}
await Promise.all(promiseArray)

If the singleObject before the promise is 'id: 1234', will the singleObject in the promise is the same ?

I know that with tests I have done it is but I can't find any documentation/example stating that the singleObject in the promise.then will be the same as the singleObject before the promise.

Does the singleObject in the promise.then is always in the same scope as the singleObject before the promise ?



Solution 1:[1]

Yes, both variables contain references to the same object. It has nothing to do with Promise.then. It's the closure of the arrow function

res => { if (res === true) { finalArray.push(singleObject) } } 

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Even the global scope is part of the closure scope chain:

Every closure has three scopes:

  • Local Scope (Own scope)
  • Outer Functions Scope
  • Global Scope

Solution 2:[2]

Not 100% sure, but I'd say the singleObject is indeed the same before and after. I believe it might be a reference to the original object ? The way to check that would be to modify one of the objects in arrayObject, and then print both arrayObject and finalArray, check if the object you modified is modified in both.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 JeanRemyDuboc