Languages
[Edit]
EN

JavaScript - if...else statement

0 points
Created by:
Rogan-Wilkes
727

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

References

  1. if...else - JavaScript | MDN

Alternative titles

  1. JavaScript - if else statement
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Statements & declarations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join