JavaScript Code


JavaScript Conditional Statements


Conditional Statements

Conditional statements are those where a block of code is executed based on the result of a condition or an expression.

In JavaScript, we have following conditional statements.

  • if – statement is used to conditionally execute a block of code.
  • if-else – statement is used to conditionally execute one of the two code blocks.
  • if-else-if – statement is used to implement a conditional ladder, to execute one of the two or more code blocks.
  • switch-case – statement is used to execute a block of code whose value matches with the given expression.

Examples

if statement

a = 10

if (a > 0) {
    console.log(`${a} is a positive number`);
}

if-else statement

a = -9

if (a > 0) {
    console.log(`${a} is a positive number`);
} else {
   console.log(`${a} is not a positive number`);
}

if-else-if statement

a = -9

if ( a > 0 ) {
    console.log(`${a} is a positive number`);
} else if ( a < 0 ) {
    console.log(`${a} is a negative number`);
} else {
    console.log(`a is zero`);
}

switch-case statement

a = 2

switch (a) {
    case 0:
        console.log("zero");
        break;
    case 1:
        console.log("one");
        break;
    case 2:
        console.log("two");
        break;
    case 3:
        console.log("three");
        break;
    case 4:
        console.log("four");
        break;
    default:
        console.log("unknown number");
}