DEV Community

JavaScript: Logical operators and Boolean Values

Banesa Guaderrama on November 15, 2018

Logical Operators ! (NOT), && (AND), || (OR) If you are learning to code or new to coding, you will be using logical operators, these ar...
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
 
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.

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
 
peter profile image
Peter Kim Frank

Great post! Just a heads up that you can highlight code like so if you'd like:

code block with no colors example

code block with colors example

Collapse
 
banesag profile image
Banesa Guaderrama

Hi Peter! Thanks for the advise, I for sure will start doing it.

Collapse
 
lexlohr profile image
Alex Lohr

The bitwise operator ^ (XOR) can also be used to evaluate if only one of both given expressions is true and can be a useful shorthand:

x ^ y === Number(x && !y || !x && y)

Since it is not a logical operator, it will cast to Number (0 = false, 1 = true), but if will accept any true-ish value, so you only need to cast to boolean if you actually require the result to be one.

Unfortunately, there's no logical XOR operator in JS as of now.

Collapse
 
banesag profile image
Banesa Guaderrama

Thanks for your input Alex! You have made more robust the post with your comment, I appreciate you took the time.