HardEvent Loop & Promises💻 Output Question

Chaining Promises with Optional Chaining and Nullish Coalescing

💡

Hint

Pay attention to how the optional chaining and nullish coalescing operators are used to handle cases where properties are missing or null

What does this output?

function fetchUserData() {
  return Promise.resolve({ id: 1, name: 'John Doe' })
}

function fetchOrderData(userId) {
  return Promise.resolve([{ id: 101, total: 100 }, { id: 102, total: 200 }])
}

fetchUserData().then(user => {
  const orderId = user?.orders?.[0]?.id ?? 'No orders found'
  console.log(orderId)
  return fetchOrderData(user.id)
}).then(orders => {
  console.log(orders)
  const total = orders?.[0]?.total ?? 0
  console.log(total)
})

Correct Output

No orders found
[ { id: 101, total: 100 }, { id: 102, total: 200 } ]
100

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