DEV Community

Tolumide Shopein
Tolumide Shopein

Posted on

Nullish Coalescing and Optional Chaining in Javascript

Nullish coalescing (??):

You might have encountered scenarios, where you needed to assign a default value to a variable(x) if the expression or variable from which the value of x is to be derived or deducted, is undefined or null but not when it is false, 0, or ''(empty string).
This is almost impossible with the popular || logical operator which you would have used to assign a different value if the boolean evaluation of the prior value (resulting from the expression or variable) is a falsy.

This would be our reference object:

const obj = {
  val: '100',
  test: 30,
  absent: 0,
  exam: 70,
  grades: {
    test: 23,
    exam: 49
  }
}
const removeScoreForAbsence = obj.absent || 0
console.log(removeScoreForAbsence) // 0

const inexistentValue = obj.valueThatDoesNotExist || 10
console.log(inexistentValue) // 10

The problem with using the || logical operator as depicted above is that if we had wanted to assign the value of obj.absent to removeScoreForAbsence regardless of its value unless it is undefined or null, then this would have been impossible since the boolean evaluation of an emptyString, false, and 0 result in falsy.

Hence, nullish coalescing. So what does nullish coalescing bring to the table? Well, it assigns the value to the variable unless it is undefined or null

const checkMe = obj.absent ?? 10
console.log(checkMe) // 0

const checkAgain = false ?? 20
console.log(checkAgain) // false

const checkNull = null ?? 25
console.log(checkNull) //25

const checkUndefined = obj.undefined ?? 35
console.log(checkUndefined) // 35

Optional Chaining (?.)

Let's assume you are a Frontend developer consuming a RESTful API with deeply nested results, where the absence of a key whose value is another object is very possible, you have probably had instances where you had to write an if/else block as dabble down the nested object, or use the && (AND) logical operator in the process of assigning your value.

Let's use a simple example here:

const obj = {
  info: {
    type: 'human',
    firstName: {
      val: 'tolumide',
      firstLetter: 't'
    }
  }
}

If we had wanted to get the value of the firstLetter in obj above, what we would usually do would be to do a sort of type or value checking to confirm the existence of such nested keys in the object before accessing its values and then do a type check before we continue with its value.

const letter = obj && obj.info && obj.info.firstName && obj.info.firstName.firstLetter

console.log(letter) //t

if(letter){doWhatever()}

With optional chaining however, we can write less code

const theLetter = obj?.info?.firstName?.firstLetter
console.log(theLetter) //t

<>

const proveIt = obj?.info?.lastName?.firstLetter ?? 'no name'

console.log(proveIt) //no name

Good luck applying this 😃👍

PS: I love feedback. If you have any please drop one below or reach out to me on.

twitter => @tolumide_ng
gitHub => @tolumide-ng

Top comments (0)