Home  >  Article  >  Web Front-end  >  Did you know that? - ?? vs ||

Did you know that? - ?? vs ||

王林
王林Original
2024-07-18 06:32:451128browse

Did you know?

What is the difference between ?? and ||?

Nullish Coalescing Operator - ??

From its sweet French name “Operator of coalescence of dummies”, a ?? b allows you to return the term a if the latter is neither null nor undefined. In the opposite case the operator returns the term b.

Here is an example that allows you to redefine this operator in JavaScript.

const result = a ?? b
const nullishCoalescingOperator = (a, b) => {
    if (a !== null && a !== undefined) {
        return a
    } 
    return b;
}

const result = nullishCoalescingOperator(a,b);

Logical Or Operator - ||

The logical OR operator is similar to the null coalescence operator except that the latter tests whether the term a is falsy .

As a reminder, here is a non-exhaustive list of falsy values ​​in JavaScript:

  • null
  • undefined
  • false
  • NaN
  • 0
  • “”

Here is an example that allows you to redefine this operator in JavaScript.

const result = a || b
const orOperator = (a,b) => {
    if (a) {
        return a;
    }
    return b;
}

Memo

Finally, here is a table which summarizes the return of the functions ?? and ||

tableau récap fonctions

Sources

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

The above is the detailed content of Did you know that? - ?? vs ||. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn