DEV Community

FloatWeb2
FloatWeb2

Posted on

Ternary if in javaScript

The ternary if in JavaScript is a shortened way of writing an if/else conditional structure in a single line. It is often used to assign a value to a variable based on a condition, in a more concise and readable way.

Syntax:
The basic syntax of the ternary if is as follows:

condition ? value if true : value if false

Explanation:
The condition is the expression that will be evaluated to check whether it is true or false. If the condition is true, the value to the left of the colon (":") will be assigned to the variable. If the condition is false, the value to the right of the colon (":") will be assigned to the variable.

Example:
An example of using the ternary if in JavaScript would be to check if a number is even or odd and assign a corresponding message to the "message" variable:

let number = 5;
let message = (number % 2 == 0) ? "The number is even" : "The number is odd";
console.log(message);

In the example above, the condition checks if the remainder of the number divided by 2 is equal to zero (if the number is even). If it is true, the message "The number is even" will be assigned to the "message" variable. If the condition is false, the message "The number is odd" will be assigned. The corresponding message is then printed to the console.

The ternary if can be useful in situations where a decision needs to be made based on a simple condition, without the need to write a longer and verbose if/else control structure. However, it is important to use it in moderation and only in situations where the resulting code is clear and readable.

Top comments (1)

Collapse
 
ant_f_dev profile image
Anthony Fung

It's often a good idea to make your variables immutable (i.e. const) if you know they shouldn't change, e.g. if they are the result of a calculation. Doing so makes bugs harder to introduce as some code that would otherwise overwrite the variable will throw an error - failing loudly is better than a silent mutation in terms of debugging.

Ternary statements are a great way to assign a variable based on a condition, while making it immutable.

Remember that formatting is an important part of readable code. One way of writing ternary statements is

const variable = condition
  ? trueValue
  : falseValue;
Enter fullscreen mode Exit fullscreen mode

Of course, the format depends entirely on both programming style and context.