if...else
In JavaScript, the condition does not have to be of type boolean. If any other type than boolean is provided in a boolean context like the if-statement, JavaScript will implicitly convert the value to boolean.
if (condition1) {
// ...
} else if (condition2) {
// ...
} else if (condition3) {
// ...
} else {
// ...
}
Short-Hand Notations
If you only want to execute one statement in the code block for if or else, it is possible in JavaScript to omit the curly brackets.
if (condition) doSomething();
// or
if (condition)
doSomething();
In general, it is not recommended because it is easy to forget to add the brackets back in when adding a second statement that should depend on the same condition.
When writing functions, it is a common pattern to omit the else block and use an early return in the if block instead. In many cases, this reduces nesting and makes the code more readable and easier to follow.
function checkNumber(num) {
let message = '';
if (num === 0) {
message = 'You passed 0, please provide another number.';
} else {
message = 'Thanks for passing such a nice number.';
}
return message;
}
// Can also be written as ...
function checkNumber(num) {
if (num === 0) {
return 'You passed 0, please provide another number.';
}
return 'Thanks for passing such a nice number.';
}
Backlinks