Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

JavaScript - Control Structures (if-else, switch, loops)

Control Structures (if-else, switch, loops)

Control structures are fundamental programming constructs that allow you to control the flow of execution in your code. They include conditional statements (if-else) and loops (for, while, do-while). Additionally, the switch statement provides a way to select one of many code blocks to be executed.

1. if-else Statement:

The if-else statement allows you to execute different blocks of code based on a condition.

let condition = true;

if (condition) {
  // Code to be executed if condition is true
} else {
  // Code to be executed if condition is false
}
 

2. Switch Statement:

The switch statement is used to perform different actions based on different conditions. It evaluates an expression and executes the corresponding case.

let fruit = 'Apple';

switch(fruit) {
  case 'Apple':
    console.log('Selected fruit is Apple');
    break;
  case 'Banana':
    console.log('Selected fruit is Banana');
    break;
  default:
    console.log('Unknown fruit');
}
 

3. for Loop:

The for loop is used to execute a block of code a specified number of times.

for (let i = 0; i < 5; i++) {
  console.log(`Iteration ${i}`);
}
 

4. while Loop:

The while loop executes a block of code as long as a specified condition is true.

let condition = true;

if (condition) {
  // Code to be executed if condition is true
} else {
  // Code to be executed if condition is false
}
 

5. do-while Loop:

Similar to the while loop, but the code block is executed at least once before the condition is checked.

let num = 5;

do {
  console.log(`Number is ${num}`);
  num--;
} while (num > 0);
 

6. Break and Continue:

  • Break: Terminates the current loop or switch statement and transfers program control to the statement following the terminated statement.
  • Continue: Skips the current iteration of a loop and continues with the next iteration.

7. Nested Control Structures:

You can nest control structures within each other to create more complex logic.

for (let i = 0; i < 3; i++) {
  if (i === 0) {
    console.log('i is 0');
  } else {
    console.log('i is not 0');
  }
}
 

These control structures allow you to make decisions and repeat actions in your code, which are crucial for building dynamic and interactive applications. Understanding when and how to use each of these constructs is essential for effective programming in JavaScript.