Nullish Coalescing Operator Refactoring

The nullish coalescing operator (??) returns its right side when its left side is nullish (null or undefined), and its left side otherwise. For example, const x = a ?? b would set x to a if a has a value, and to b if a is null or undefined.

The nullis…


This content originally appeared on DEV Community and was authored by Lars Grammel

The nullish coalescing operator (??) returns its right side when its left side is nullish (null or undefined), and its left side otherwise. For example, const x = a ?? b would set x to a if a has a value, and to b if a is null or undefined.

The nullish coalescing operator is very useful to provide default values when a value or an expression is nullish. Before it was introduced in ES2020, this default value pattern was often expressed using the conditional operator.

You can replace conditional (ternary) checks with nullish coalescing operator expressions:

  • a == null ? x : a becomes a ?? x
  • a != null ? a : x becomes a ?? x
  • a === null || a === undefined ? x : a becomes a ?? x
  • a !== null && a !== undefined ? a : x becomes a ?? x
  • etc.

Learn More: Nullish coalescing operator (MDN)

P42 now supports converting ternaries that provide default values for nullish expressions. The refactoring is available on the playground and for all repositories. Try it out!


This content originally appeared on DEV Community and was authored by Lars Grammel


Print Share Comment Cite Upload Translate Updates
APA

Lars Grammel | Sciencx (2021-05-08T18:47:56+00:00) Nullish Coalescing Operator Refactoring. Retrieved from https://www.scien.cx/2021/05/08/nullish-coalescing-operator-refactoring/

MLA
" » Nullish Coalescing Operator Refactoring." Lars Grammel | Sciencx - Saturday May 8, 2021, https://www.scien.cx/2021/05/08/nullish-coalescing-operator-refactoring/
HARVARD
Lars Grammel | Sciencx Saturday May 8, 2021 » Nullish Coalescing Operator Refactoring., viewed ,<https://www.scien.cx/2021/05/08/nullish-coalescing-operator-refactoring/>
VANCOUVER
Lars Grammel | Sciencx - » Nullish Coalescing Operator Refactoring. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/08/nullish-coalescing-operator-refactoring/
CHICAGO
" » Nullish Coalescing Operator Refactoring." Lars Grammel | Sciencx - Accessed . https://www.scien.cx/2021/05/08/nullish-coalescing-operator-refactoring/
IEEE
" » Nullish Coalescing Operator Refactoring." Lars Grammel | Sciencx [Online]. Available: https://www.scien.cx/2021/05/08/nullish-coalescing-operator-refactoring/. [Accessed: ]
rf:citation
» Nullish Coalescing Operator Refactoring | Lars Grammel | Sciencx | https://www.scien.cx/2021/05/08/nullish-coalescing-operator-refactoring/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.