JavaScript Logical and Conditional Operators Explained

3 Min Read

blog img

As JavaScript developers, we often find ourselves writing code that checks conditions and evaluates expressions. While if-else statements serve this purpose well, JavaScript provides us with several other, more concise ways to deal with conditionals and logical operations: the ternary (conditional) operator ? :, the nullish coalescing operator ??, the logical AND operator &&, and the logical OR operator ||.

Each of these operators brings a unique flavor to our code, helping us handle null, undefined, true, false, and other values in specific ways. This blog post is dedicated to providing a deeper understanding of these powerful tools in our JavaScript toolkit.

The Ternary (Conditional) Operator ? :

Starting our journey is the only ternary operator in JavaScript — the conditional operator ? :. This operator deals with three operands and acts as a sleek alternative to if-else statements, particularly when assigning variables based on a condition.

Check out its syntax:

condition ? valueIfTrue : valueIfFalse

Now, let’s see it in action:

const isEven = (num) => num % 2 === 0 ? "Even" : "Odd" 
console.log(isEven(7)) 
// "Odd"

With the ternary operator, you can make your code cleaner and easier to read, adding a touch of elegance to your style. 😎

The Nullish Coalescing Operator ??

Fresh from ES2020, the nullish coalescing operator ?? is a go-to tool when you need to offer a fallback value for null or undefined.

Here’s how to use it:

let result = value ?? defaultValue;

And here it is in action:

let settings = { 
	animationDuration: 0, 
	showSplashScreen: undefined 
} 
 
let animationDuration = settings.animationDuration ?? 300 
let showSplashScreen = settings.showSplashScreen ?? true 
 
console.log(animationDuration) // 0 
console.log(showSplashScreen) // true

Got undefined values lurking in your code? Fear not! The nullish coalescing operator is here to the rescue! 🥳

The Logical AND Operator &&

The logical AND operator && is the perfect partner when you need to check if all conditions are truthy. If it encounters a falsy value, it stops and returns that value. If all it sees are truthy values, it gives you the last truthy value.

const value1 = true && “Hello” // “Hello” 
const value2 = 0 && “Hello” // 0

If you’re a React developer, you’ve likely seen and used this operator in conditional rendering. If not, no worries it’s never too late to join the && fan club! 😉

The Logical OR Operator ||

Rounding off our operator exploration, the logical OR operator || helps you provide an alternative value when the original value is falsy. It delivers the first truthy value it comes across, or the last falsy value if no truthy value is found.

const value1 = true || “Hello” // true 
const value2 = undefined || “Hello” // “Hello”

Tired of undefined sneaking up on your functions? With the logical OR operator, you can set alternative values and keep your functions running smoothly. 🚀

Real-World Use Cases

These operators truly shine when used in real world coding scenarios. For instance, React developers frequently use the logical AND && operator for conditional rendering. This operator allows you to decide whether or not to render a component based on certain conditions. Here’s a quick example:

{isLoggedIn && <WelcomeMessage />}

In this case, <WelcomeMessage /> is only rendered if isLoggedIn is truthy.

Also, when working with CSS frameworks like Tailwind CSS, these operators come in handy for conditional styling. For instance:

<div className={`h-16 w-16 ${isActive ? ‘bg-green-500’ : ‘bg-red-500’}`}> 
{/* content */} 
</div>

In the code snippet above, we use the ternary operator to change the background color of a div based on whether the isActive state is truthy or falsy.

Conclusion

There you have it, folks! We’ve toured through some of JavaScript’s logical and conditional operators, seen them in action, and looked at some real world applications.

These operators are indispensable tools in your JavaScript toolbox, helping you to write cleaner, more expressive, and more concise code. Whether you’re checking conditions, assigning values, or handling null and undefined, these operators are there to help.

As always, I’ll continue to share more insights and experiences in the exciting world of JavaScript. To join me on this journey:

Let’s continue exploring the vast universe of coding together. Happy coding! 😃


Level Up Coding

Thanks for being a part of our community! Before you go:

🔔 Follow us: Twitter | LinkedIn | Newsletter

🚀👉 Join the Level Up talent collective and find an amazing job