DEV Community

Sasireka
Sasireka

Posted on

Conditional Statements

1. Conditional Statements in JavaScript.

  • In JavaScript,conditional statements control the flow of execution in a program by performing different actions based on whether a condition is true or false.

  • The main types of conditional statements are if, else, else if, the switch statement.

if Statement : The if statement is the most basic conditional, executing a block of code only if the specified condition evaluates to true.

  • Syntax :

if (condition)
{
// Code to execute if the condition is true
}

if...else Statement : The if...else statement provides an alternative block of code to run when the condition in the if statement is false.

  • Syntax :

if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}

  • Example

let i = 10;
if(i>=5)
{
console.log("True")
}
else
{
console.log("False")
}
//output: True

if...else if...else Statement : This structure allows to check multiple conditions sequentially. The program executes the block of the first condition that evaluates to true and skips the rest.

  • Syntax :

if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition1 is false and condition2 is true
}
else
{
// Code to execute if all conditions are false
}

  • Example :

let mark = 75;
if(mark >= 90)
{
console.log("A Grade")
}
else if(mark >=60 && mark<90)
{
console.log("B Grade")
}
else
{
console.log("C Grade")
}
//output: B Grade

switch Statement : The switch statement is an alternative to a long if...else if chain when you are testing a single expression against many possible fixed values.

  • Syntax :

switch (expression)
{
case value1:
// Code to execute if expression matches value1
break; // Important to exit the switch block
case value2:
// Code to execute if expression matches value2
break;
default:
// Code to execute if no case matches
}

  • Example :

let fruit = "apple";
let message = "";
switch (fruit)
{
case "banana":
message = "It's a banana!";
break;
case "orange":
message = "It's an orange!";
break;
case "apple":
message = "It's an apple!";
break;
default:
message = "Unknown fruit";
}
console.log(message);
//output: It's an apple!

Top comments (0)