OR
console.log('---- OR ----');
// Use ANY data type, return ANY data type, short-circuiting
console.log(3 || 'Jonas');
console.log('' || 'Jonas');
console.log(true || 0);
console.log(undefined || null);
console.log(undefined || 0 || '' || 'Hello' || 23 || null);
Output ->
3
Jonas
true
null
Hello
OR tries to find the earliest truthy value and if none available it returns -> NULL.
NULL, 0, undefined, '' -> all are considered as falsy values
For the restaurant object defined before ->
restaurant.numGuests = 0;
const guests1 = restaurant.numGuests ? restaurant.numGuests : 10;
console.log(guests1);
const guests2 = restaurant.numGuests || 10;
console.log(guests2);
Output ->
10
10
Because even 0 is considered as a falsy value
AND
Tries to check if there is even 1 falsy value then it returns false else true.
console.log(0 && 'Jonas');
console.log(7 && 'Jonas');
console.log('Hello' && 23 && null && 'jonas');
Output ->
null
Jonas
null
For eg ->
if (restaurant.orderPizza) {
restaurant.orderPizza('mushrooms', 'spinach');
}
//can be re-written as
restaurant.orderPizza && restaurant.orderPizza('mushrooms', 'spinach');
In the below statement the restaurant.orderPizzatries && to check if restaurant.orderPizza exists or not and then calls it replacing the need for an if statement.
Nullish Coalescing operator
So the operator ?? just returns truthy values for (0 and '') and falsy values for (null and undefined).
const rest1 = {
name: 'Capri',
// numGuests: 20,
numGuests: 0,
};
const rest2 = {
name: 'La Piazza',
owner: 'Giovanni Rossi',
};
rest1.numGuests ??= 10;
rest2.numGuests ??= 10;
rest1.owner &&= '<ANONYMOUS>';
rest2.owner &&= '<ANONYMOUS>';
console.log(rest1);
console.log(rest2);
Output ->
It checks whether the owner property of rest1 and rest2 are defined . Sine it is false for rest1 so it doesn't go further but for rest2 it is defined and dos it goes forward to the owner property to be assigned as