Code Premix

Ternary Operators in JavaScript

📅May 19, 2024

Ternary operators in JavaScript are like the Swiss Army knives of decision-making in code. They’re these nifty little shortcuts for writing if-else statements in a single line. These operators help streamline your code, making it more concise and easier to read. Let’s delve into the world of JavaScript ternary operators and see how they can simplify your coding journey.

1. Ternary Operator (?)

The ternary operator is composed of three parts: a condition followed by a question mark, a value if true, and a value if false.

let result = (age >= 18) ? 'Adult' : 'Minor';

2. Usage in Assignments

Ternary operators can be used to assign values based on conditions in a compact way.

let isMorning = (time < 12) ? 'Good morning!' : 'Good day!';

3. Returning Values from Functions

They’re handy for returning different values based on conditions in functions.

function getDiscount(isPremium) {
  return (isPremium) ? 20 : 10;
}

4. Nesting Ternary Operators

You can nest them to handle more complex conditions, but beware of readability.

let num = 15;
let type = (num % 2 === 0) ? 'Even' : (num % 3 === 0) ? 'Divisible by 3' : 'Odd';

Conclusion

Ternary operators in JavaScript are your go-to buddies for streamlining if-else statements. They help condense your code, making it more elegant and easier to maintain. Incorporating these operators into your coding arsenal can enhance your code’s readability and efficiency.

Happy coding!

With ternary operators in your toolkit, your code becomes a sleek, efficient decision-maker, simplifying complex conditions.