EN
JavaScript - if...else statement
0
points
In this article, we would like to show you how to use if...else statement in JavaScript.
Description
The if
statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed using else if
or else
keyword.
Syntax
if (condition) {
// statement 1
} else {
// statement 2
}
Practical examples
Example 1 - simple if...else
// ONLINE-RUNNER:browser;
let x = 1;
if (x == 1) {
console.log('x is equal to 1');
} else {
console.log('x is not equal to 1');
}
Output:
x is equal to 1
Example 2 - multiple if...else
// ONLINE-RUNNER:browser;
let x = 1;
if (x > 0) {
console.log('x is a positive number');
} else if (x < 0) {
console.log('x is a negative number');
} else {
console.log('x is equal to 0');
}
Output:
x is a positive number