The Nullish coalescing operator (??)

The Nullish coalescing operator (??)

The Nullish coalescing operator (??) is a new operator introduced in ECMAScript 2020 (also known as ES11). It is used to provide a default value when a variable is null or undefined.

In JavaScript, when you want to set a default value for a variable that could be null or undefined, you often use the logical OR (||) operator. For example:

No alt text provided for this image
Logical Operator OR ||

However, this approach has a limitation: if the variable is falsy, but not null or undefined (e.g., it could be an empty string or the number 0), the default value will still be assigned. For example:

No alt text provided for this image

To solve this problem, the Nullish coalescing operator (??) was introduced. It only checks for null or undefined values, and ignores other falsy values. For example:

No alt text provided for this image

In this way, the Nullish coalescing operator allows you to more accurately and safely provide default values for variables that may be null or undefined

要查看或添加评论,请登录

Ahmad Joya的更多文章

  • Website Performance Optimization

    Website Performance Optimization

    Optimize Images and Media: Images and other media files can significantly impact page load times. Compress images to…

  • JavaScript Console Methods

    JavaScript Console Methods

    Remember, in programming, the details make the difference between a junior and senior developer. Learning how to…

  • Conventional Commit Message and Linting

    Conventional Commit Message and Linting

    These are common commit message prefixes or types that can be used to indicate the purpose of a commit in a project's…

    1 条评论
  • Apple v. FBI: How to Sound Smart about Encryption

    Apple v. FBI: How to Sound Smart about Encryption

    How to Sound Smart about Encryption

社区洞察

其他会员也浏览了