How to write an inline IF statement in JavaScript ?
An inline if statement in JavaScript is also known as a ternary operator. It is a shorthand way of writing an if-else statement in a single line. The syntax for an inline if statement is as follows:
condition ? expressionIfTrue : expressionIfFalse
Here, condition
is the expression that is evaluated, expressionIfTrue
is the value returned if the condition is true, and expressionIfFalse
is the value returned if the condition is false.
For example, let's say we want to check if a number is even or odd and print a message accordingly. We can use an inline if statement as follows:
const num = 5;
console.log(num % 2 === 0 ? "Even" : "Odd"); // Output: Odd
In this example, the condition num % 2 === 0
checks if the number is even or not. If it is true, the expression "Even"
is returned, otherwise, the expression "Odd"
is returned.
Another example of using an inline if statement is to check if a variable is null or undefined and assign a default value to it. We can do this as follows:
let name = null;
const defaultName = "John Doe";
name = name ? name : defaultName;
console.log(name); // Output: John Doe
In this example, the condition name
checks if the variable name
is null or undefined. If it is true, the expression defaultName
is assigned to name
, otherwise, the value of name
remains unchanged.