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

Did you know that? - ?? vs ||

王林
Release: 2024-07-18 06:32:45
Original
1145 people have browsed it

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
Copy after login
const nullishCoalescingOperator = (a, b) => {
    if (a !== null && a !== undefined) {
        return a
    } 
    return b;
}

const result = nullishCoalescingOperator(a,b);
Copy after login

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
Copy after login
const orOperator = (a,b) => {
    if (a) {
        return a;
    }
    return b;
}
Copy after login

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!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template