JavaScript’s IF Else shorthand syntax is a powerful tool that allows you to write concise and readable code. In this tutorial, we will explore some tips and tricks for using this shorthand syntax effectively.
1. Basic IF Else Shorthand syntax
The basic syntax for the IF Else shorthand in JavaScript is as follows:
condition ? valueIfTrue : valueIfFalse;
This syntax allows you to check a condition and return different values based on whether the condition is true or false.
For example, let’s say we want to check if a number is greater than 10 and return “yes” if it is true, and “no” if it is false. We can do this using the IF Else shorthand like this:
const number = 15;
const result = number > 10 ? “yes” : “no”;
console.log(result); // Output: “yes”
2. Nested IF Else Shorthand
You can also nest multiple IF Else shorthand statements to handle more complex conditions. For example, let’s say we want to check if a number is positive, negative, or zero and return a corresponding message. We can achieve this with nested IF Else shorthand like this:
const number = 7;
const result = number > 0 ? “positive” : number < 0 ? "negative" : "zero";
console.log(result); // Output: "positive"
3. Using IF Else Shorthand in Function
You can also use the IF Else shorthand syntax within a function to return different values based on a condition. For example, let's create a function that checks if a number is even or odd and returns a message accordingly:
const checkEvenOrOdd = (number) => number % 2 === 0 ? “even” : “odd”;
console.log(checkEvenOrOdd(10)); // Output: “even”
console.log(checkEvenOrOdd(15)); // Output: “odd”
4. Default value using IF Else Shorthand
You can also use the IF Else shorthand to provide a default value if a variable is undefined or null. For example, let’s say we want to assign a default value of 0 to a variable if it is undefined:
let num;
const result = num ?? 0;
console.log(result); // Output: 0
5. Handling multiple conditions
You can use the IF Else shorthand in conjunction with logical operators (&& and ||) to handle multiple conditions. For example, let’s say we want to check if a number is divisible by both 2 and 3:
const number = 6;
const result = (number % 2 === 0) && (number % 3 === 0) ? “divisible by 2 and 3” : “not divisible by 2 and 3”;
console.log(result); // Output: “divisible by 2 and 3”
In conclusion, the IF Else shorthand syntax in JavaScript is a powerful tool that allows you to write clean and concise code. By following the tips and tricks outlined in this tutorial, you can make your code more readable and maintainable. Experiment with different scenarios and conditions to master the use of IF Else shorthand in JavaScript.