[X]

Javascript Conditional Statements - (Learning Javascript Series)

Javascript Conditional Statements

There are two conditional statements in JavaScript: if and switch. The if statement allows the program to choose one of two alternatives, based on some predefined factor.

If statement: It is used to interrupt program flow for some condition.

var num = 10;
                if (num < 20) {
                    alert(num + " is less than 20.");
                }

If - Else: It is used to interupt program flow for some condition but instead of satisfying for one, it will also check for second condition.

var num = 10;
                if (num < 20) {
                    alert(num + " is less than 20.");
                }
                else {
                    alert(num + " is greater than 20.");
                }

If - Else if - Else: It is used to check for 2 conditions and if none of them is true than do some default action.

var num = 10;
if (num < 0) {
    alert(num + " is negative.");
}
else if (num > 0) {
    alert(num + " is positive.");
}
else {
    alert(num + " is 0.");
}

Switch statement

This has a very similar to If-Else if - Else. but if we have more than 3 conditions to check, switch statement can be more effective and readable. It has switch along with different cases. Every case is followed by a break statement which tells to stop once current case is satisfied. If break is not used statement will skip to next case even if current case is satisfied. We also use Default case to provide a default behavior in case none of the case is meet.

 

var countryCode = "CA";
var fullCountryName;
switch (countryCode) {
    case "IN": fullCountryName = "India"; break;
    case "US": fullCountryName = "United States"; break;
    case "UK": fullCountryName = "United Kingdom"; break;
    case "", "?":
    default: fullCountryName = "Unknown country code";
}
alert(fullCountryName);

 

 

blog comments powered by Disqus

Posts By Month