Answers for "null coalescing on nested object js"

0

null coalescing on nested object js

// Have you used this?
if (response.data && response.data.temperature) {
  highTemperature = response.data.temperature.high;
}

// Optional chaining provides a terse alternative. 
// This is JavaScript’s version of the 'safe navigation' operator

const highTemperature = response.data?.temperature?.high;

// In addition to accessing nested values, 
// another common pattern in JavaScript is to use the logical OR operator (||) 
// to coalesce values because it returns the first truthy operand, not a Boolean.
const defaultTime = 2;
const animationTime = settings.animationTime || defaultTime; 
// if animationTime is set to 0 --> 0 is falsy, so will result in default time 2 instead of 0

const animationTime = settings.animationTime ?? defaultTime;
// ?? only rejects values if they are strictly null or undefined
Posted by: Guest on February-10-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language