DEV Community

Discussion on: JavaScript: Logical operators and Boolean Values

Collapse
 
andreandyp profile image
André Michel Andy

Great article! Don't forget that && and || use short-circuit evaluation, useful for use cases like feature flags and set default values:

//if flag is true, then execute this function
process.env.FLAG && someFunc();

//Instead of...
const var2 = var1 ? var1 : "something";
//...use || operator
const var2 = var1 || "something";
Enter fullscreen mode Exit fullscreen mode
Collapse
 
banesag profile image
Banesa Guaderrama

Hi André! Thank you for your comment. With just some lines you have provided a great input about default values.

Collapse
 
merudo profile image
Guillaume F.

Yes!

As a reminder, the logical operators work the following way with non-boolean values:

expr1 && expr2: If expr1 is truthy, returns expr2; else, returns expr1.
expr1 || expr2: If expr1 is truthy, returns expr1; else, returns expr2.