Skip to content

Instantly share code, notes, and snippets.

@mamboer
Created August 14, 2024 02:53
Show Gist options
  • Save mamboer/95ef5e45bc7d469d956201593f62da6e to your computer and use it in GitHub Desktop.
Save mamboer/95ef5e45bc7d469d956201593f62da6e to your computer and use it in GitHub Desktop.
Typescript

在 TypeScript 和 JavaScript 中,?? 和 || 都是用于处理默认值的运算符,但它们的行为略有不同。

??(空值合并运算符, Nullish Coalescing Operator)

  • 用途:用于处理 null 或 undefined 的情况。
  • 行为:如果左侧操作数是 null 或 undefined,则返回右侧操作数;否则返回左侧操作数。
const value = someVariable ?? 'default value';

||(逻辑或运算符, Logical OR Operator)

  • 用途:用于处理假值(falsy values),包括 false0''(空字符串)、nullundefinedNaN
  • 行为:如果左侧操作数是任何假值,则返回右侧操作数;否则返回左侧操作数。

区别

  • ?? 只处理 nullundefined,而 || 处理所有假值。
  • 使用 ?? 可以避免误将 0false'' 视为需要替换的值。

示例

const nullValue = null;
const undefinedValue = undefined;
const falseValue = false;
const zeroValue = 0;
const emptyStringValue = '';

console.log(nullValue ?? 'default'); // 输出: 'default'
console.log(undefinedValue ?? 'default'); // 输出: 'default'
console.log(falseValue ?? 'default'); // 输出: false
console.log(zeroValue ?? 'default'); // 输出: 0
console.log(emptyStringValue ?? 'default'); // 输出: ''

console.log(nullValue || 'default'); // 输出: 'default'
console.log(undefinedValue || 'default'); // 输出: 'default'
console.log(falseValue || 'default'); // 输出: 'default'
console.log(zeroValue || 'default'); // 输出: 'default'
console.log(emptyStringValue || 'default'); // 输出: 'default'
💡 Tips on using `Typescript`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment