ES6 Ternary Operator

The ES6 Ternary Operator is a shorthand way of writing conditional statements in JavaScript. It allows you to write a single line of code that evaluates an expression and returns one value if the expression is true and another value if the expression is false.

Here is the basic syntax of the ternary operator:

				
					condition ? expressionIfTrue : expressionIfFalse
				
			

Here’s an example that uses the ternary operator to assign a value to a variable based on a condition:

				
					const age = 18;
const canVote = age >= 18 ? "Yes" : "No";
console.log(canVote); // "Yes

				
			

In this example, the condition is age >= 18, which is true because the age variable is equal to 18. The expression after the ? is “Yes”, which is the value that is returned if the condition is true. The expression after the : is “No”, which is the value that is returned if the condition is false.

Here’s another example that uses the ternary operator to return different JSX components based on a condition in a React application:

				
					return (
  <div>
    {isLoggedIn ? <LogoutButton /> : <LoginButton />}
  </div>
);

				
			

In this example, the isLoggedIn variable is a boolean that determines which component to render. If isLoggedIn is true, the LogoutButton component is rendered, otherwise the LoginButton component is rendered.

Overall, the ternary operator is a powerful tool for writing concise conditional statements in JavaScript. It can make your code easier to read and write, especially in cases where you need to evaluate a condition and return a value in a single line of code.

Join To Get Our Newsletter
Spread the love