Logical Or operator || vs Nullish Coalescing
In JavaScript and TypeScript, the `||` operator is often used to provide a default value in case a variable is "falsy", meaning it's `undefined`, `null`, `0`, `NaN`, empty string `''`, or `false`.
For example:
let value = userDefinedValue || 'default';
In this snippet, if `userDefinedValue` is `undefined`, `null`, or any other falsy value, `value` will be set to `'default'`.
However, this can be problematic. For instance, if a user intentionally sets `userDefinedValue` to `0` or `''`, this logic will still replace `userDefinedValue` with `'default'`, which is probably not what the user intended.
Enter nullish coalescing operator `??`. It's similar to `||`, but it only returns the right-hand side if the left-hand side is `null` or `undefined`.
Example:
let value = userDefinedValue ?? 'default';
Now, `value` will only be set to `default` if `userDefinedValue` is `undefined` or `null`. This way, intentioned falsy values (such as `0` or `''`) are preserved, making the nullish coalescing operator a more predictable way to handle defaults.
Comments
Post a Comment