Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Control structures in Javascript

In this chapter, you will learn about the control structures in Javascript. The very first control structure is the if-else statement. Now lets us see the syntax and write an example for the same.

Control structures in Javascript

if-else statement:
Syntax of the if-else statement:

if (condition1) {

} else if (condition2) {

} else if (condition3) {

} else {
    
}

if-else is conditional control structure, helps to execute the part code which matches or passes the predefined condition. And if else statement takes the decision. Let’s look at the below example, we are checking whether the user has admin access or not.

let user = {
    name: 'John',
    isAdmin: true,
    isActive : false
};

if(user.isAdmin === true || user.isActive === true) {
    console.log('User has admin access');
    console.log('Execute this part of the code');
} else {
    console.log('User dont have admin access');
    console.log('Execute this part of the code');
}

// out put
// User has admin access
// Execute this part of the code

Switch statement:
Syntax:

switch (condition) {
    case '1':
        break;
    case '2':
        break;
    case '3':
        break;
    default:
}

When several conditions become more, it will be a bit complicated with an if-else block statement. In that case, the Switch statement can be used to make it easy. Let’s take a look on below code snippet.

let condition = '1';

switch (condition) {
    case '1':
        console.log('Execute the first part of the code');
        break;
    case '2':
        console.log('Execute the first part of the code');
        break;
    case '3':
        console.log('Execute the first part of the code');
        break;
    default:
        console.log('The default case');
}

// output
// Execute the first part of the code
Block statement
  1. The most basic statement is a block statement
  2. The block is delimited by a pair of curly brackets
  3. Block statements are commonly used with control flow statements (if, for, while)
let x = 1;
while (x < 10) {
  x++;
}
console.log(x);
// 10

 

One thought on “Control structures in Javascript

Comments are closed.