The Very Useful JavaScript Ternary Operators

The JavaScript ternary operators are used when a variable is determent based on certain conditions. The ternary operators are similer to the if statement in a way they both execute some code based on different condition. But unlike multiple lines of code can be executed when some conditions are met with the if statement, the ternary operators can only assign a variable a value when some coditions are stisfied.

JavaScript Ternary Operators Syntax

The JavaScript ternary operators look like this:
var x = (conditions) ? value assign to x if some conditions are met : 
value assign to x if some conditions are not met;

Chaining JavaScript Ternary Operators

The JavaScript ternary operators can be chained when there are layers or steps of conditions that need to be checked.

Chianing Example

 var age = 6;
 var gender = "male";
 var whatAmI = age < 24 ? gender == "male " ? "boy" : "girl" : gender == "male " ? "man" : "woman";
 console.log(whatAmI);
 //girl

Examples of doing the same thing with if statement and the ternary operators

Here are some examples of the same thing done by the if statement and the ternary operators. Sometimes with the help with the ternary operators, our code could be a lot simpler.

Change the color of a button with if statement

<button onclick="
	if(this.style.backgroundColor == 'lightgreen'){
		this.style.backgroundColor = 'pink';
	}else{
		this.style.backgroundColor = 'lightgreen';
	};
" style="background-color: lightgreen;">Click Me</button>

Change the color of a button with ternary operators

<button onclick="
this.style.backgroundColor = this.style.backgroundColor == 'lightgreen' ? 'pink':
'lightgreen'" style="background-color: lightgreen;"
>Click Me</button>

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser