DEV Community

Dharshini E
Dharshini E

Posted on

JavaScript - Control Flow Statements

Control Flow Statements :
1.What is Control Flow?

Control flow is the order in which JavaScript executes code. By default, it’s top-to-bottom. But with control flow statements, you can:

  • Run a block of code only if a condition is true.
  • Run code repeatedly using loops.
  • Jump out of loops early or skip certain steps.

** Conditional Statements in JavaScript**

  1. if statement: Executes a block of code only when the condition is true. example:
let age = 20;

if (age >= 18) {
  console.log("You are an adult.");
}
Enter fullscreen mode Exit fullscreen mode

2.if else Statement:

Provides two different paths: one if the condition is true, another if it’s false.
example:

let age = 16;

if (age >= 18) {
  console.log("You can vote.");
} else {
  console.log("You are too young to vote.");
}
Enter fullscreen mode Exit fullscreen mode

3.switch Statement:

A cleaner way to compare the same value with many cases.
example:

let day = 3;

switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Other day");
}
Enter fullscreen mode Exit fullscreen mode

Loops:
Loops let you repeat code until a condition is false.
1.for loop:
Runs a block of code a fixed number of times by using an initializer, condition, and increment/decrement.
example:

for (let i = 1; i <= 5; i++) {
  console.log("Number " + i);
}
Enter fullscreen mode Exit fullscreen mode

2.while loop:
Keeps running as long as the condition is true; checks the condition before each run.
example:

let i = 1;
while (i <= 5) {
  console.log("Count: " + i);
  i++;
}
Enter fullscreen mode Exit fullscreen mode

3.do while loop:
Runs the block at least once, then repeats as long as the condition is true.
example:

let i = 1;
do {
  console.log("Value is " + i);
  i++;
} while (i <= 3);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)