Skip to content
the poor coder

JS Ternary

Poor Man
Published
Reading time
1 min read

JS Ternary#

JS Ternary operator is a shorthand version of an if-else statement. It is often used to assign a value to a variable based on a condition.

Syntax:#

Text
condition ? trueValue : falseValue;

The condition is the expression that needs to be evaluated. If the condition is true, then the trueValue is returned, else the falseValue is returned.

Let's say you want to assign a value to a variable based on whether a number is even or odd. You can use the ternary operator to achieve this:

Text
let num = 10;
let result = num % 2 === 0 ? "even" : "odd";
console.log(result); // Output: even

In this example, the condition is num % 2 === 0, which returns true when num is even. If the condition is true, then the value "even" is assigned to result, else the value "odd" is assigned to result.

You can also nest ternary operators to make more complex decisions:

Text
let age = 18;
let result = age < 18 ? "Underage" : age < 25 ? "Young Adult" : "Adult";
console.log(result); // Output: Young Adult

In this example, if the age is less than 18, then the value "Underage" is assigned to result. If it is not, then the next condition age < 25 is evaluated. If it is true, then the value "Young Adult" is assigned to result. If it is false, then the value "Adult" is assigned to result.

The ternary operator is a concise and powerful way to make decisions in JavaScript.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC