Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between && and ?? in JavaScript

I am trying to use Logical AND && and Nullish coalescing operator ?? operators for the conditional rendering of variables/values. But for some reason, I am unclear about the usage of both of these operators and how they work.

Please explain the difference between both of these and when should we use any of those instead of if statement.

/* --------------------  ?? operator -------------------- */
const foo = null ?? '?? default string';
console.log(foo);

const baz = 0 ?? 10;
console.log(baz);

/* --------------------  && operator -------------------- */

const foo_1 = null && '&& default string';
console.log(foo_1);

const baz_1 = 0 && 20;
console.log(baz_1);
like image 262
Ahmad Habib Avatar asked Apr 13 '26 00:04

Ahmad Habib


1 Answers

To see the difference and to determine when to use one operator or another, you can make a table like this:

                        |    ||   |    &&   |    ??   |
    --------------------+---------+---------+---------+
        0, 'default'    |'default'|    0    |    0    |
       '', 'default'    |'default'|   ''    |   ''    |
    false, 'default'    |'default'|  false  |  false  |
     null, 'default'    |'default'|   null  |'default'|
undefined, 'default'    |'default'|undefined|'default'|
     true, 'default'    |  true   |'default'|  true   |
       20, 'default'    |   20    |'default'|   20    |
like image 79
Alexandr Belan Avatar answered Apr 15 '26 14:04

Alexandr Belan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!