Conditional statements in JavaScript alter the program flow, and by using a conditional flow, you can make your program make choices about what should happen based on certain conditions.
JavaScript comes with a number of conditional statements (a.k.a control structures) that can alter the program flow, and an example of such are if, switch, and even ternary operators that make the JavaScript interpreter execute or skip other statements depending on the value of a certain expression.
It also has statements like while and for loops that give us the ability to write code that would execute more than once without the need of writing the code over and over again.
We would look into various types of conditional statements in JavaScript, first...
if Statement
The if statement is the control statement that makes a conditional statement based on a certain expression.
It has the following syntax:
if (expression) statement;
The expression is going to evaluate to True or False, and if the expression is truthy, it is going execute the statement, if otherwise or the expression is falsy, the statement will not be executed, it is that simple, let’s see an example:
let $j = 5; let $k = 2;
if ($j === $k) {
console.log("j is equals to k");
}
This would run the statement within the if statement if the expression($j === $k) is True, in which case, it isn’t, let’s modify the code:
let $j = 5; let $k = 5;
if ($j === $k) {
console.log("j equals to k");
}
// => "j equals to k"
Now, you get the idea, it evaluated the statement as the expression is True, which in our case $j equals to $k.
Here are more examples:
let $userName // declare variable
if ($userName == null) // If username is null or undefined,
$userName = "Mr. Pascalo"; // define it
As you can see we aren't using a curly bracket to enclose the expression, this is fine if you would only be testing one condition, if you would testing many, then you would want to use the curly bracket to separate each, in short, I'll advise using a curly bracket even if you are only testing one condition, this would make for clearer code:
let $userName; // declare variable
if ($userName === null) { // If username is null or undefined,
$userName = "Mr. Pascalo"; // define it
}
Extending if with else
There are cases where a script or code would be required to continue regardless of the result of the if condition. What to do when it is true, as well as, false. This is where the else if or else keyword comes to play, it allows the execution of one block of code when the condition is true and another when the condition is evaluated as false.
To extend our already existing code, we can do:
let $j = 5; let $k = 3;
if ($j == $k) {
console.log("j equals to k");
} else {
console.log("j is not equals to k");
}
// => "j is not equals to k"
So, what we did above is simply if the first statement is not True, do the second statement, but if the first statement is True, it would skip the else code right away.
Here is another example:
let num = 6;
if (num === 1) {
console.log("You have 1 new notification.");
} else {
console.log(`You have ${num} new notifications.`);
}
// => You have 6 new notifications
In addition to else, we also have elseif, and that strings multiple conditions together, for example:
let num;
if (!num) { // If num is null, undefined, false, 0, "", or NaN, do the following statement
console.log("You have no new notification.");
} else if (num === 1) {
console.log(`You have 1 new notifications.`);
} else {
console.log(`You have ${num} new notifications.`);
}
// => You have no new notification.
If the first one matches, it would do the first statement, if the second matches, it would execute the second, and if no one of the two matches, it would default to else. In our case, the first expression matches.
You can have multiple else-if statements, but make sure you default to else if anything doesn’t match. Feel free to test more examples yourself.
Switch-Case Statements
We previously looked at creating conditional statements using if and else but there are cases where using case statements makes the logic simpler, and clearer.
The thing is, if-statement causes a branch in the flow of a program's execution, and you'll often test multiple conditions along the line. While this is a good solution to test multiple conditions, it is not really a viable solution when all of the branches depend on the value of the same expression.
The switch case statement can make this kind of logic clearer and simple, the following is the syntax of a switch statement:
switch (value) {
case value_to_test1:
statement or block of codes
break; // stop here if the case is true
case value_to_test2:
statement or block of codes
break; // stop here if the case is true
default: // if all the cases fails, do below statement
statement
}
We use the switch statement followed by an argument, which might be a value, and that value is what we are going to be testing through each of a series of test cases.
The test cases are within the switch curly brace, it starts with the case keyword, and what you are testing against. So basically, the switch statement will first expand the expression and then it will try to match it in turn with each specified case.
When a match is found, all the statements within that case are executed.
If no match is found, the statement that is defined by the default would be executed, this is similar to the else statement.
Note the break keyword used at the end of each case in this code.
The break statement causes the interpreter to break out of the switch statement and continue with the statement that follows it.
Here is an example that checks user grade:
let $grade = 'B';
switch ($grade) {
case 'A':
console.log("Excellent Result!");
break;
case 'B':
console.log("Very Good Result!");
break;
case 'C':
console.log("Good Result!");
break;
case 'D':
console.log("Fairly Good, You can try better next time");
break;
default:
console.log("Not Impressive, but you could do a lot better next year");
break;
}
// => Very Good Result!
We assigned a value to the variable $grade, so we need a way to test user grade by using the switch statement, so, all we need to do is to test the variable $grade and that is why I had switch($grade) and in the case where it is ‘A’, we execute a statement, in the case where it is ‘B’, we execute a statement, and so on. If it doesn’t match anything we are expecting, we execute the default case.
As you can see, I am enclosing the value cases in a single-quotes, this is because I am testing against a string, if I am testing against an integer, you don’t need a single quote, e.g:
let $j = 2;
switch ($j) {
case 0:
console.log("j equals 0");
break;
case 1:
console.log("j equals 1");
break;
case 2:
console.log("j equals 2");
break;
}
// => j equals 2
It tested the case in series, and it then matches case 2, this is like saying, in the case where $j is 2, print the statement, you get the idea.
Note, the way the switch-case statement works in JavaScript or most programming language is a bit crazy, if you do not provide the break keyword, it would keep matching the other cases, see an example:
let $j = 0;
switch ($j) {
case 0:
console.log("j equals 0");
case 1:
console.log("j equals 1");
case 2:
console.log("j equals 2");
}
// j equals 0
// j equals 1
// j equals 2
It would keep matching them in turn, and keep executing the case statement, so, you need to explicitly write the break keyword, which is very annoying, but it is what it is.
Now, let’s improve on how our grade code, the below is an improved version:
let $grade = 'B';
switch ($grade) {
case 'A':
case 'B':
case 'C':
console.log("Excellent Result!");
break;
case 'D':
console.log("Fairly Good, You can try better next time");
break;
default:
console.log("Not Impressive, but you could do a lot better next year");
}
// => Excellent Result
If you are in a situation where you would like to execute the same statement for different cases, you can write them one after the order, without using the break keyword, so, in the example above, we tested for Cases A, B, and C, and if it matches anything of the sort, the statements that are related to the Case A, B, and C gets executed once, this is much more faster and better than using if/else statement or by writing the same statement for each cases.
Another good advantage of using a case statement instead of an if/else statement is that the expression you are comparing with is only evaluated once in a switch statement, while in an if/else statement, it keeps on re-evaluating, see the following example:
let $i = 0; // $i is still 0
if(++$i == 3) { // $i would be incremented, so it is 1
console.log(3);
}
else if(++$i == 2) { // $i would be incremented, so it is 2, and in that case, it would match
console.log(2);
}
else if (++$i == 1) {
console.log(1);
}
else {
console.log("No match!");
}
// => 2
As you can see above, it would keep re-evaluating the expression, which is why it matches ++$i == 2, this can cause a serious bug if it is not intended, but consider the following example using switch-case:
let $i = 0;
switch (++$i) {
case 3:
console.log(3);
break;
case 2:
console.log(2);
break;
case 1:
console.log(1);
break;
default:
console.log("No Match");
}
// => 1
The answer to this is 1 because the switch statement would only evaluate once, unlike the if/else statement that would re-evaluate for each cases, this is also good when you have a function that returns a certain value, and you only want to evaluate it once, this can be much faster.
So, when should you use either of the two, I’ll say use if/else if you want to evaluate several variables to find the first one with an actual value, something like:
let $a = 1; let $b = 2;
if ($a > $b) {
echo "a is larger than b";
} else if ($a < $b) {
echo "a is smaller than b";
}...
There is no way you can do that with a switch as it only accepts a single expression e.g switch(n), but if we think of this, we can implement a logic that uses a Boolean TRUE, in the line of switch(TRUE) which would evaluate each and every case, see an example:
let $i = 2; let $k = 4;
switch (true) {
case ($i > $k):
console.log("i is larger than k");
break;
case ($i < $k):
console.log("i is lesser than k");
break;
default:
console.log("No Match");
}
// => i is lesser than k
Switch (true) would keep evaluating, so make sure you have your break keyword in place when an expression matches as I have done above.
While some would argue that this isn’t a better construct, IMO, it’s all about preference, and in fact, this type of logic is used on a regular occasion when programming in bash, I wrote one here: Multiple Menus in Bash Script
Do whatever makes the most sense to you. So, really, you can perform anything if/else can perform using a switch-case statement and even better 😉
In the next section, we would look into Loops.
Loops give us the ability to write code that would execute more than once without the need of writing the code over and over again.
Imagine having to edit 10,000 lines of text within a CSV file, this would be a shit load of work if done manually, which is where looping comes in. When a task or a series of tasks needs to be repeated, it can be put inside a loop.
We would look into various types of loops, e.g While Loops, For Loops, and a couple of ways to enhance the Loops using the break and continue statements, let’s start with…
While Loops
A while loops while the condition is true, the code executes once, and then it loops back to the start to execute again. Each time the code executes, it might change the values and variables each time it goes through the loop.
The syntax of a while loop is as follows
while (expression){
statement;
}
This is really easy to understand if you think of them in the following way: While the expression evaluates to True, keep executing or looping through the statements.
Let’s see an example:
let $count = 10;
let $n = 0;
while ($count >= 0) {
console.log( `${++$n} Welcome To Devsrealm\n`);
$count--;
}
// Output
/*
1 Welcome To Devsrealm
2 Welcome To Devsrealm
3 Welcome To Devsrealm
4 Welcome To Devsrealm
5 Welcome To Devsrealm
6 Welcome To Devsrealm
7 Welcome To Devsrealm
8 Welcome To Devsrealm
9 Welcome To Devsrealm
10 Welcome To Devsrealm
11 Welcome To Devsrealm
*/
This prints "Welcome To Devsrealm" 11 times because you are saying while the count is greater than 0 or equal to 0, so, when the count gets to 0, it still prints the statement before breaking out of the loop. If you want to print the "Welcome To Devsrealm" 10 times, then you need to do: while ($count >= 1)
The above example prints “Welcome To Devsrealm” 11 times, it does the following:
- We set an initial value of where the count should begin, in this case, we want the count to begin at 10; $count =10
- We then say, “while the count is greater than or equal to 0, do the next step, for the first run, it is true, we have 10, so…
- It prints “Welcome To Devsrealm”
- count-- reduces the count by 1, you can also write it as count=count – 1
- As soon as the count reaches -1, it skips the while loop altogether
If you want to print "Welcome To Devsrealm" 10 times, then you do:
let $count = 10; let $n = 0;
while ($count >= 1) {
console.log( `${++$n} Welcome To Devsrealm\n`);
$count--;
}
// Output
/*
1 Welcome To Devsrealm
2 Welcome To Devsrealm
3 Welcome To Devsrealm
4 Welcome To Devsrealm
5 Welcome To Devsrealm
6 Welcome To Devsrealm
7 Welcome To Devsrealm
8 Welcome To Devsrealm
9 Welcome To Devsrealm
10 Welcome To Devsrealm
*/
This prints "Welcome To Devsrealm" 10 times because you are saying while the count is greater than 1 or equal to 1, so, when the count gets to 1, it still prints the statement before breaking out of the loop.
If that feels confusing, you can do:
let $count = 10; let $n = 0;
while ($count > 0) {
console.log( `${++$n} Welcome To Devsrealm\n`);
$count--;
}
/*
1 Welcome To Devsrealm
2 Welcome To Devsrealm
3 Welcome To Devsrealm
4 Welcome To Devsrealm
5 Welcome To Devsrealm
6 Welcome To Devsrealm
7 Welcome To Devsrealm
8 Welcome To Devsrealm
9 Welcome To Devsrealm
10 Welcome To Devsrealm
*/
While the count is greater than zero(0) keep printing, as long as it is no longer greater than 0, break out of the loop. So, as it gets to 0 > 0, it breaks out as 0 can never be greater than 0.
One thing you need to note is that the loop needs to have a condition, and an expression that will allow it to execute, and secondly, something about the condition has to change during the course of the loop, if anything doesn’t change, it would be an infinite loop, which is not something you would want.
For example, if we remove the $count--, you would get an infinite loop:
let $count = 10;
let $n = 0;
while ($count > 0) {
console.log( `${++$n} Welcome To Devsrealm\n`);
//$count--;
}
(n) Welcome To Devsrealm - Infinity
It would print “Welcome To Devsrealm” forever, and this is because 10 is always greater than zero(0), so, something has to change or you need to somehow reduce the value until you get out of the loop, you can't just keep on going forever.
Here is an example that corrects it:
let $count = 0;
while ($count <= 10) {
console.log(`${$count}`);
$count++;
}
/*
0
1
2
3
4
5
6
7
8
9
10
*/
So, again, we did the following:
- We set an initial value of where the count should begin, in this case, we want the count to begin at 0; $count =0
- We then say, “while the count is lesser than or equal to 0, do the next step, the first run is true, we have 0, so…
- It prints 0
- count++ increases the count by 1, you can also write it as count=count + 1
- As soon as the count reaches 11, it skips the while loop altogether
I guess this clarifies while loops in Javascript, to log the result on a single line, we can concatenate the numbers to a string, this way we can keep track of it:
let $count = 0; let output = "";
while ($count <= 10) {
/*
# Concatenate every result of $count, and store it in the variable output.
# += is used to add a value to an already existing value, we then uses the + " "
# to give it spacing
*/
output += $count + " "; // can also be written as output = output + $count + " "
$count++;
}
console.log(output); // => 0 1 2 3 4 5 6 7 8 9 10
Another way you can use the while loop is by using do/while as follows:
do
statement
while (expression);
The do/while loop is like a while loop, except that the loop expression is tested at the bottom of the loop rather than at the top. This means that the body of the loop is always executed at least once. You can use whatever feels okay for you.
For Loops
A for loop is similar to a while loop, in that it loops while the condition is true, the code executes once, and then it loops back to the start to execute again.
The syntax of for loops is a bit more classical than while loop, here is the syntax:
for (init; test; increment) {
statement;
}
Instead of setting the initial value outside of the loop, like the way we did it in the while loop, you put that in expression 1(init), so, it would be executed the first time only.
Expression 2(test) is what we are evaluating or what we are testing, and expression 3(increment) is going to be executed at the end of every loop; an example is the count++ we used in the while loop.
Putting them all in the first line of the loop makes it easy or clearer to understand what a for loop is doing and prevents mistakes such as forgetting to initialize or increment the loop variable.
The following is an example of for loop:
let $count = 0; let output = "";
for ($count = 0; $count <= 10; $count++) {
console.log($count)
}
/ => /*
0
1
2
3
4
5
6
7
8
9
10
*/
Again, to log the result on a new line, we can concatenate the numbers to a string, this way we can keep track of it:
let $count = 0; let output = "";
for ($count = 0; $count <= 10; $count++) {
/*
# Concatenate every result of $count, and store it in the variable output.
# += is used to add a value to an already existing value, we then uses the + " "
# to give it spacing
*/
output += $count + " "; // can also be written as output = output + $count + " "
}
console.log(output); // => 0 1 2 3 4 5 6 7 8 9 10
As you can see it is exactly the same, for loop just gives us a better structure of how everything relates.
Note: Make sure you are not adding a semi-colon to the third expression, here: $count++
So, feel free to use whatever loops feel right to you.
You can also have multiple initializations by using the comma operator:
let i, j, sum = 0;
for(i = 0, j = 5 ; i < 5 ; i++, j--) {
sum += i * j; // can also be written as sum = sum + i * j;
}
console.log(sum) // => 20
So, again, we did the following:
- We set 2 initial value of where the count should begin, in this case, we want the i count to begin at 0 (i = 0), and the j count to begin at 5 (j = 5), note that we are using the comma operator to separate the initialization
- We then say, “while i is lesser than 5, increment i, and decrement j, so, as long as i is not more than 5, we keep incrementing and decrementing j
- For the first run the i would be 1, j would be 4, and the sum would be sum = 0 + 1 * 4, which gives us 4, now the sum is 4, then the second run i would be 2, j would be 3, and the sum would be sum = 4 + 2 * 3, which gives us 10. The third run is sum = 10 + 3 * 2, which equals = 16, fourth run is sum = 16 + 4 * 1, and that is 20. The fifth run, I would be incremented to 5, and since we said as long as i is lesser than 5, keep incrementing i and decrementing j, it would jump out of the loop as that is true.
Here is an illustration:
As you can see, as soon as the i got to 5, it breaks out from the loop. If you want to write an infinite loop in for, you can do for(;;) just like while(true).
for/of
If you are familiar with other programming languages, e.g PHP, for/of is the same as for each loop. For/of loop is a different from a while and for loops, a for/of loop lets you iterate (perform again) over a series of words within a string or a list of items, or an array.
So, it is going to take an array, and then loop through each item of the array until it gets to the end.
When we are using while loops or for loops, we know when to quit or keep looping by testing if a condition has been met, on the other hand, For/of loops knows when to quit by whether items are left in the list or the array to loop over.
The syntax of for/of loop is as follows:
for($item of $data) {
statement;
}
As you can see the syntax is a bit different from the loops we’ve seen so far, the for/of loop takes $data, which is what you would be looping through (it doesn’t have to be called $data, you can call it $list or whatever you feel makes the most sense), we have a special keyword “of” and the $item (it doesn’t have to be called $value) is going to be assigned an item as it loops through the items in the $data.
Note: The $data should be something that exists beforehand, you can’t just loop through a list that does not exist, on the other hand, the $item doesn’t exist, it is just a placeholder for holding the value.
Another thing to note is that when using while or for loops, we create a couple of conditions that tell the loop when to start, incrementation, and when to stop, when using for/of loop, you don’t need that, it knows when to start the loop, when to go to the next line, and when to end the loop, well, that is because the condition for exiting is when it gets to the end of the array.
Here is an example:
let $data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], $sum = 0, $item="";
for($item of $data) {
$sum += $item; // can also be written as $sum = $sum + $item
}
console.log($sum) // => 55
We created an array that stores numbers 1 -10 in the $data variable, this is going to store the list of what we are going to loop through. So, we started with the for keyword, and we then declare $item to be the variable that will take different values contained in $data array, what we are basically doing is reading from the list on the right to populate the variable parameter ($item) on the left.
Here is another example:
let $list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], $number ;
for($number of $list) {
console.log(`Number: ${$number}\n`);
}
// =>
/*
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
*/
We created an array that stores numbers 1 -10 in the $list variable, this is going to store the list of what we are going to loop through. So, we started with the for keyword, and we then declare $number to be the variable that will take different values contained in the $list array, what we are basically doing is reading from the list on the right to populate the variable parameter ($number) on the left.
Imagine, you have the item listed in the following order:
- 1
- 2
- 3
- ….
- 10
The $list contains the array items, so the first time the loops goes, it would assign the first item, in this case, 1, and store it in the $number variable, within the for/of loop, we are printing the output of the $number variable, it then goes over to pick number 2 until there is nothing left in the array. That is the idea of a for/of loop, as long as there are items to be processed in the list, the loop will execute until the list is exhausted.
To calculate the frequency that a character appears in a word, you can do:
let freq = {}, char ="";
for(char of "Devsrealmer") {
if (freq) {
freq++;
} else {
freq = 1;
}
}
console.log(freq) // =>
{
D:1,
e:3,
v:1,
s:1,
r:2,
a:1,
l:1,
m:1
}
By checking if(freq) you are checking if the value of freq is falsey (i.e: empty string (" "), undefined, 0, null, etc.). If it is true, we add + 1 each time it is true, else it equals 1.
There is also a similar loop, which is for/in:
The difference between for..in and for..of is that for..in iterates over all enumerable property keys of an object, while, for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.
for (item in object)
statement
Controlling the Loop with Break and Continue
What if at some point, we need to exit the loop prematurely or perhaps exclude certain items from processing, For this scenario, we have loop control keywords, such as break and continue.
You’ve already seen examples of the break statement within a switch statement. In loops, it is typically used to exit prematurely when, for whatever reason, there is no longer any need to complete the loop.
So, here is the distinction: The break keyword is used to break out of a loop, be it a for or while loop, while the continue keyword is used to end the current iteration in a loop, but continue with the next iteration.
Let’s see an example that creates an odd number with for loops and the continue statement:
let odd = "";
for (let $i=0; $i <= 10; $i++) {
if ($i % 2 == 0) { continue; }
odd += $i + " ";
}
console.log(odd) // => 1 3 5 7 9
An odd number is an integer that can’t be divided by 2, Odd numbers when divided by 2, leave a remainder other than zero(0). Using that definition we can write a program that does that, all we need to do is create a condition that terminates the current iteration whenever the current number returns zero when divided by 2, which is why we have:
if ($i % 2 == 0) { continue; }
For example, the first count is zero (0), and when divided by 2 returns zero(0), the loop terminates the current iteration and goes to the next digit, which is 1, so, when you have 1 divide 2, it returns a reminder other than zero, so, it continues the operation, so, that is the idea of how it works.
You can do the same for an even number, so, you just check if the reminder is not == 0, if the reminder is not == 0, it means it is an odd number, we then use the continue statement to skip it:
let even = ""; for (let $i=0; $i <= 10; $i++) { if ($i % 2 !== 0) { continue; } even+= $i + " "; } console.log(even) // => 0 2 4 6 8 10
You can achieve the same stuff with a while loop:
Disclaimer: There is a problem with the below code, I'll explain...
let even ="";
let $i = 0;
while ($i <= 10) {
if ($i % 2 == 0) {
continue;
}
even += $i + " ";
$i++;
}
console.log(even)
We have an infinite loop on line 3, which is not what you would want, what happens is as soon as you get to the modulus condition, the loop got stuck. We said if $i (which is 0) divide by 2 returns zero(0), it should continue, and that goes back to the top of the loop, here:
while ($i <= 10)
and it evaluates $i is less than or equal to 10 and $i is zero, so, it goes back to the modulus condition and keeps looping around forever, we are not incrementing it, to fix that, you do:
let $i = 0, even = "";
while ($i <= 10) {
if ($i % 2 == 0) {
$i++;
continue;
}
even += $i + " ";
$i++;
}
console.log(even) // 1 3 5 7 9
Now, before we continue the modulus condition, we increment it, it is as simple as that. This doesn't happen in for loop because it does the incrementation at the beginning stage of the loop, so, that is the reason why some people prefer it.
Let's get into the break statement, it breaks out of the loop entirely, consider the following example:
let $count = "'
for (let $i=0; $i <= 10; $i++) {
if ($i == 5) {
break;
}
$count += $i + ", ";
}
console.log($count); // => 0, 1, 2, 3, 4,
As soon, as the $i variable gets to 5, it breaks out of the loop entirely unlike a continue statement that would cancel the current iteration, and move on with the next one.