MediumEvent Loop & Promises💻 Output Question

Deep Copy vs Shallow Copy with Promises

💡

Hint

Consider the difference between changing a primitive value and a nested object in both the shallow and deep copies.

What does this output?

let original = { a: 1, b: { c: 2 } }
let shallowCopy = { ...original }
let deepCopy = JSON.parse(JSON.stringify(original))

Promise.resolve().then(() => {
  shallowCopy.a = 10
  shallowCopy.b.c = 20
  deepCopy.a = 30
  deepCopy.b.c = 40
  console.log(original.a, original.b.c)
  console.log(shallowCopy.a, shallowCopy.b.c)
  console.log(deepCopy.a, deepCopy.b.c)
})

Correct Output

1 2
10 20
30 40

Why this output?

More Event Loop & Promises Output Questions

EasySynchronous code runs before setTimeoutMediumPromise microtask before setTimeout macrotaskMediumPromise chain passes valuesHardTwo Promise chains interleave in microtask queue

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz