DEV Community

Discussion on: What's new in JavaScript - ES2020

Collapse
 
blacklight profile image
Fabio Manganiello • Edited
  • The optional chaining is probably one of the most requested features from any developer sick of "some_variable_name is null" errors. I see that it's already been rolled out in the most recent versions of Firefox and Chrome - waiting for the new versions to get enough tractions before throwing away lots of ifs in my code :)

  • I don't see the big win of using Promise.allSettled over the old Promise.all. Promise.allSettled would also return if any of the promises fails, but in my use cases I've always been ok with wrapping Promise.all into a try/catch for those cases.

  • I don't see the big difference between the new nullish coalescing syntax with ?? and simply using the dear ol' ||.

Collapse
 
gautemeekolsen profile image
Gaute Meek Olsen • Edited

I agree with you there 😊

For the last two points, they might be useful for some use cases. But like you say, you might not need it and use what you describe.

  • Promise.all might not be sufficient if you need the value from the promises that resolves. Here is an example where Promise.all will log the error and not be able to get the result from the resolved promises. The Promise.allSettled will be able to get the result from the resolved promises. But again, this is only for use cases when you don't need all promises to resolve to continue.
// Promise.all with try catch
try{
  const [r1, r2] = await Promise.all([Promise.resolve(1), Promise.reject(2)])
  console.log({r1, r2}) // never runs and we won't get r1 value
}catch(error){
  console.log({error}) // logs error
}

// Promise.allSettled
const [r1, r2] = await Promise.allSettled([Promise.resolve(1), Promise.reject(2)])
console.log({ r1, r2 }) // can use r1 even though r2 rejected
  • Nullish coalescing can be useful to avoid default values for falsy values that should be set. Think of this example where a user has set preferred sound-level to zero, we don't want to overwrite this with the default sound value which is 50. Which, we only want for users who have never set the preferred sound-level.
const user = { preferredSound: 0 }
let sound = user.preferredSound ?? 50 // value is 0
let soundWrong = user.preferredSound || 50 // value is 50

edit: updated article with these examples to clarify.

Collapse
 
octaneinteractive profile image
Wayne Smallman

Yeah, optional chaining is a good introduction.

I would have done something like: if (house.hasOwnProperty('owner') { ...

… which isn't practical on deep objects.