Javascript conditional operator

conditions

If, else and switch are conditional statement or operators in javascript. Conditional statement changes the flow of the program according to test cases. So if the block contains test expression inside the parenthesis. if the test expression is evaluated is true then the body of if executed and if the test expression is evaluated is false then the body of else executed and body of it will be skipped. Let us see the basic structure for if and else.


if (condition) { //true condition case }
else { //else condition case }

The if statement


// simple if statement
var msg;
if (!msg) msg = "Welcome to inside if statement";
console.info(msg); // Welcome to inside if statement

The if and else statement


//if and else statement
var msg = null;
if (!msg) msg = "if statement";
else msg = "Sorry right now we are else statement";
console.info(msg); // if statement

The else statement


// else if statement
var msg = null;
if (!msg) msg = "if statement";
else if (msg == "first") msg = "first else if";
else if (msg == "second") msg = "secons else if";
else msg = "Sorry right now we are else statement";
console.info(msg); // if statement

Curly brackets {} is optional if there’s just one statement, but semicolon is still required. We can use ternary operator like if else.


//ternary expression
var msg = null;
var msg = (!msg) ? "New Msg" : "Old Msg";
console.info(msg); // New Msg

The switch statement

JavaScript’s “switch” does fall-through. It’ll jump to a matching point and run all of the rest of case code without testing.


// switch
var msg = 1;
switch (msg) {
    case 1:
        msg = "first case";
        console.log(msg);
    case 2:
        msg = "second case";
        console.log(msg);
    default:
        msg = "Sorry right now we are in the default case";        
}
console.info(msg); // Sorry right now we are in the default case

You can see our output is default block because in this can your all cases executed and your last case replaced all the value of msg.


// switch with break
var msg = 1;
switch (msg) {
    case 1:
        msg = "first case";
        console.log(msg);
        break;
    case 2:
        msg = "second case";
        console.log(msg);
        break;
    default:
        msg = "Sorry right now we are in the default case";        
}
console.info(msg); // first case

Shorthand for switch using if statement


// Useful switch using if statement
function x() {
    console.info("I am inside x");
}

function y() {
    console.info("I am inside y");
}

var cases = {
    1: x,
    2: y
};

var i = 1;

if (cases[i]) {
    cases[i](); // I am inside x
}

You May Also Like

About the Author: Pankaj Bisht