In JavaScript If, Else, and Switch are conditional statements. Those are a piece of code executed based on certain conditions if evaluated into true. Like JavaScript every programming languages has those statements, those are the fundamentals of the programming.
In this guide we will discuss about what are those? why you need it? and how you can use them to improve you programming skills.
Content List
- What control flow means in programming
- The if statement
- The if-else statement
- The else if ladder
- The switch statement
- When to use switch vs if-else
What control flow means in programming
In JavaScript code execute line-by-line. When code load into JS environment, the interpreter read it from top line to the bottom line and executre it. The order of reading code by JavaScript interpreter in sequence called control flow.
look at the bellow image:
In the code visualization you see the 15 lines of code. When it load in Js environment, Interpreter read and execute it form line 1 to 16. During the execution iterpreter see the conditional statements at line 9 if(user.isLoggedIn) and 11 else. It allow program to either be executed or skipped line 10 console.log("Jump to profile screen") or 12 console.log("Jumpt to login screen"). in our case line 10 statement will executed and statement at line 12 will skipped.
The if statement
If statements use to define a control flow statement.
// Syntax:
if(condition){
// statement
}
It use a condition and a statement, if condition evaluated into true the statement code will executed other wise it will skiped. Lets see example:
const age = 44
if(age>0 && age<100){
console.log("valid age: ", age)
}
In above code example if the given condition evaluated into true than code statement will execute otherwise its skipped.
The if-else statement
The else clause used to execute statement when condition evaluated to false.
// Syntax:
if(condition){
// Statement A
} else {
// Statement B
}
It always need to used with if clause other wise interpreter throws error. If your statments is inline than you can skip the curly braces {}. Lets see Example:
const age = 17
if(age>0 && age<100){
console.log("Age is valid: ", age)
}else{
console.log("Age is invalid: ", age)
}
In the given code if the condition evaluated into true than statement A will executed other wise statement B.
The else if ladder
Using else if ladder allow to use multiple condition to executed as many statements as we want. You can use else if statement to do this.
// Syntax:
if(condition A){
// Statement A
} else if (condition B){
// Statement B
} else{
// Statement C
}
The flow is go throw every statement, first check for condition A if its evaluted to false then move to next condition B and so on untile reach to last condition or else statement if exist. Lets see Example:
// Vote System
const age = 19
if(age >= 18 && age <= 100){
console.log("You can vote, your eligible: ", age)
} else if(age > 0 && age < 18){
console.log("You can not vote, your not eligible: ", age)
} else{
console.log("Please give valid age", age)
}
In the given code if the age is greater than or equal to 18 and lesser or equal to 100 than it's valid age for statement A, in second condition if age is greather than 0 and lesser to 18 than it's valid for staement B, if both condition is failed than last else caluse handle it. In our case the first condition setisfy it so you see the statement A will executed.
Do It Your Self: Create a grade system in there check score if score is greather than 80 or lesser or equal to 100 than give a grade A+. If score is greather than 50 or lesser or equal to 80 than give a grade A. If score is greather than 35 or lesser or equal to 50 than give grade B and handle the fail condition using else with grade F.
The switch statement
If you check a multiple conditions based on single value so instead using if-else statements you can use switch-case statements. Which are more readable and optimized for these types of control flow.
switch(expression){
case lable 1:
statement A
break;
case lable 2:
statement B
break;
case lable 3:
statement C
break;
default:
statement D
}
Here a single expression is evaluated and matched to each label in the flow if any one is matched than corresponding statement will executed and control flow transfered to outside the switch statement by break keyword. If non of them are matched than default statement are executed if exist.
The break keyword is optional but it mostly used with it. It normally stop to matching remaing labels when one them had matched. If not using it the control flow is not transfered untile all labels are matched.
const dayNumber = new Date().getDay();
let dayName;
switch(dayNumber){
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Unknown Day";
}
console.log("Today is: ", dayName)
In the above code, day number is matched to every day in the week one-by-one using switch-case stament. if one of them matched. The control flow transfered to the last console which print today day. If non of them are matched than default value is used.
Do It Your Self: Try to replicate this example by own self. Run it in you JavaScript environment and test will it give the correct output or not.
When to use switch vs if-else
There are few consideration for using switch-case and if-else statements to keep in mind:
Use if-else statements when you are handling complex logical conditions. But if you are only need to checking fixed value like numbers, and strings and matching it to specific case value than using switch-case is batter.
Using if-else with multiple statements and nesting them each other making it hard to read. Its easier to read switch-case labaled statements.
Its rarely noticable with small code base. Using if-else statements making code slower as compare to switch-case. Because switch-case use some type of jump table which help it to jumpt to specific label and than evaluate each condition sequenctially.
Using switch-case and if-else statement claverly make you a good programmer. If you following all practise than it will make you understanding good on these conditional statements. If you need to read official or more docs you can try bellow resources which i read to write this guid.




Top comments (0)