&& and || Operators don’t return boolean values
Do you really know JavaScript
1 min readNov 4, 2023
I always thought && and || returned boolean. And I was wrong!
&& returns first falsy value
|| returns first truthy value
Consider the following code snippet
let first = 1;
let second = "a";
let third = null;
let fourth = true;
console.log(first && second && third && fourth) // Consoles out null
Now let’s update the values and see how || behaves
first = null;
second = undefined;
third = "a";
fourth = false;
console.log(first || second || third || fourth); // Consoles out "a"
And yes both the operators do short circuit!
🎉 React use case
In case you are rendering a list and adding a condition to check if the list is empty, something like below
const App = () => {
return list.length && <List list={list} />;
}
If list.length is 0, then && will return 0 and React will render it on screen
Instead, we can do something like this
const App = () => {
return list.length > 0 ? <List list={list}/> : null;
}
Thanks!