Jul 4, 2024
if-else
statements and switch
statements.if-else
statement in one line.condition ? exprIfTrue : exprIfFalse
condition
: The condition to evaluate (e.g., age >= 18
).exprIfTrue
: Expression to execute if condition is true (e.g., console.log('I like to drink wine')
).exprIfFalse
: Expression to execute if condition is false (e.g., console.log('I like to drink water')
).age
:
const age = 23;
if-else
logic:
age >= 18 ? console.log('I like to drink wine') : console.log('I like to drink water');
I like to drink wine
if age is 23 because the condition is true.I like to drink water
if age is 15 because the condition is false.const drink = age >= 18 ? 'wine' : 'water';
console.log(drink);
// Outputs: 'wine'
if-else
blocks:
let drink;
if (age >= 18) {
drink = 'wine';
} else {
drink = 'water';
}
console.log(drink);
// Outputs: 'wine'
console.log(`I like to drink ${age >= 18 ? 'wine' : 'water'}`);
// Outputs: 'I like to drink wine'
if-else
statements.if-else
is still needed for executing larger blocks of code based on conditions.if-else
statements to single-line expressions.