Hiển thị các bài đăng có nhãn ||. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn ||. Hiển thị tất cả bài đăng

Difference between || and ?? operators

 https://stackoverflow.com/questions/61480993/when-should-i-use-nullish-coalescing-vs-logical-or

The OR operator || uses the right value if left is falsy, while the nullish coalescing operator ?? uses the right value if left is null or undefined.

These operators are often used to provide a default value if the first one is missing.

But the OR operator || can be problematic if your left value might contain "" or 0 or false (because these are falsy values):

console.log(12 || "not found") // 12
console.log(0  || "not found") // "not found"

console.log("jane" || "not found") // "jane"
console.log(""     || "not found") // "not found"

console.log(true  || "not found") // true
console.log(false || "not found") // "not found"

console.log(undefined || "not found") // "not found"
console.log(null      || "not found") // "not found"

In many cases, you might only want the right value if left is null or undefined. That's what the nullish coalescing operator ?? is for:

console.log(12 ?? "not found") // 12
console.log(0  ?? "not found") // 0

console.log("jane" ?? "not found") // "jane"
console.log(""     ?? "not found") // ""

console.log(true  ?? "not found") // true
console.log(false ?? "not found") // false

console.log(undefined ?? "not found") // "not found"
console.log(null      ?? "not found") // "not found"

While the ?? operator isn't available in current LTS versions of Node (v10 and v12), you can use it with some versions of TypeScript or Node:

The ?? operator was added to TypeScript 3.7 back in November 2019.

And more recently, the ?? operator was included in ES2020, which is supported by Node 14 (released in April 2020).

When the nullish coalescing operator ?? is supported, I typically use it instead of the OR operator || (unless there's a good reason not to).

Double question mark in Typescript & Javascript

 Double question mark in Typescript & Javascript | Nullish Coalescing (??) Operator (shareablecode.com)


Usage of ?? Sign in JavaScript and TypeScript

It returns second parameter when first parameter happens to be undefined or null. 

const value = firstParam ?? secondParam;

What's the difference between ?? and || in JavaScript / TypeScript

A common approach to achieve similar thing we use:

const value = firstParam || secondParam;

But problem is logical operator evaluates false value as well, which is not null or undefined

const foo = false
const baz = foo || 'default value'; // returns 'default value'
const value = foo ?? 'default value'// returns false;

Renewing Facebook Graph API token automatically?

  Mã truy cập dài hạn https://developers.facebook.com/docs/facebook-login/guides/access-tokens/get-long-lived/ https://community.n8n.io/t/re...