DEV Community

Max
Max

Posted on

3 1

Conditional Statements in JavaScript: If-Else

Conditional statements are used in programming to used execute specific code based on certain conditions. In JavaScript, if else execute based on the return value of the conditional statement.

The If-Else Statement

syntax:

if (condition) {
  // execute this block of code if condition is true
} else {
  // execute this block of code if condition is false
}
Enter fullscreen mode Exit fullscreen mode

Here, condition is an expression that evaluates to either true or false. If condition is true, the code inside the first set of curly braces will be executed. If condition is false, the code inside the second set of curly braces will be executed.

Example:

let score = 40;

if (age >= 40) {
  console.log("You scored above 40");
} else {
  console.log("You scored below 40");
}
Enter fullscreen mode Exit fullscreen mode

In this example, if score is greater than or equal to 40, the message "You scored above 40" will be printed to the console. If score is less than 40, the message "You scored below 40" will be printed.

The If-Else If Statement

The if-else if statement can be used when there are multiple conditions that need to be evaluated.

syntax:

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition2 is true
} else {
  // code to be executed if all conditions are false
}
Enter fullscreen mode Exit fullscreen mode

Here, if condition1 is true, the code inside the first set of curly braces will be executed. If condition1 is false and condition2 is true, the code inside the second set of curly braces will be executed. If both condition1 and condition2 are false, the code inside the third set of curly braces will be executed.

Example:

let volt = 150;

if (volt >= 200) {
  console.log("Voltage above 200");
} else if (volt >= 175) {
  console.log("Voltage above 175");
} else if (volt >= 150) {
  console.log("Voltage above 150");
} else if (volt >= 100) {
  console.log("Voltage above 100");
} else {
  console.log("Voltage below 100");
}
Enter fullscreen mode Exit fullscreen mode

In this example, while check the volt value in if else if statement third one is valid, Voltage above 150 will be printed in the console. Condition below the statement are valid but it won't execute because the one if statement is already valid.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series