The JavaScript Journey #8 - Control Flow

in #programming6 years ago

Flowing river

Have you ever watched The Flash? If you have, first of all, your taste in good acting is not that commendable. Lame jokes aside, The Flash is a great analogy because of him screwing up the timelines all the freaking time. Every time a new timeline is created, a new reality comes into existence. This new dimension has a flow, just like a river, which we can see and monitor.

What's this guy talking about?

The concept of control flow is as old as programming itself. Since the beginning, programmers have been trying to solve problems which arise from different conditions found in the code. Rarely does a program ever have a linear flow of execution. But let's explore this occurrence.

We have a simple variable named apple and we'll give it the string value of 'red'.

var apple = 'red';
console.log(apple);

We'll also just a regular console.log() statement just beneath it to log the value to the console. Every JavaScript program will execute from top to bottom. The simple example from above will assign the value 'red' to the apple variable and log the value to the console in that particular order. These two statements will be executed in sequence, one after the other. This is the most common representation of linear control flow.

red apple

Adding conditions to screw up the time-lines

When talking about conditional execution of code, we first need to understand the concept of a conditional statement. It is the act of choosing one of two, or more, paths given to us. In the conditional statement, there are multiple realities which co-exist, just like the multiple dimensions from the various timelines The Flash screwed up. It's up to us to guide the program down one of those paths based on the input we provide it.

Let's meet a new keyword. Say hello to the if statement! Okay, that was underwhelming. So... What does it do? Let's say we want some code to be executed if, and only if, a certain condition is valid. View the example above once again. What if we wanted to log the value of the variable only if it was ' green'? Let's modify the code slightly.

var apple = 'red';
if (apple === 'green') {
  console.log(apple);
}

An if statement is written by adding the keyword if, followed by a pair of braces and a pair of curly braces. The value in between the braces must be equal to a Boolean. It's this Boolean expression which determines whether the code between the curly braces will execute or not. If it is true it will be run, otherwise, it will not. Simple enough!

the multiverse

The multiverse!

It will be more than rare to just have code which executes when a condition holds true. You need a way to handle the remaining case. Without further ado, voilà! Introducing the else keyword. By using it in conjunction with the if keyword we can create two separate, non-overlapping execution paths. Or, to make it sound immensely cooler, two totally different dimensions!

var apple = 'red';
if (apple === 'green') {
  console.log(apple);
} else {
  console.log('The apple is not green.');
}

But, for us, two is not enough. We need more. Thankfully, chaining multiple if-else pairs is a viable option when you need to handle more than two possible execution paths.

var apple = 'red';
if (apple === 'green') {
  console.log(apple);
} else if (apple === 'red') {
  console.log('The apple is red.')
} else {
  console.log('The apple is not green, not is it red.');
}

Here the second path will be chosen and the console with get logged with the string 'The apple is red.'. Programming is beautiful. We're creating branches in the execution context just by specifying multiple if statements. Could you believe, there is a possibility one of these conditions may never be met. The code would in that case never be run. Like it never existed in the first place. Now that shit is deep.

switching it up

Switching it up

Once you have many if-else chains, it becomes cumbersome to read and handle such code. That's where the switch statement comes into play. More often than I'd like to admit, I see code such as this.

if (apple == "green") doThis();
else if (apple == "red") doThat();
else if (apple == "yellow") doSomethingElse();
else defaultAction();

It's sloppy and all over the place. This is where the switch statement shines. It's the perfect solution for when you have several conditions to cover.

switch (apple) {
  case "red":
    console.log("The apple is red.");
    break;
  case "green":
    console.log("A green apple.");
    // this will continue to the statement below
  case "yellow":
    console.log("A yellow apple.");
    break;
  default:
    console.log("Unknown apple color!");
    break;
}

You add the variable you wish to check in the braces after the switch statement. This will be checked against all the case labels. There can be as many cases you wish. You have no constraints here. What does it mean for us? We're creating multiple time-lines, but only one will become reality! The limits between the time-lines are the break statements.

Once control flow enters the switch statement, it will jump to the label that corresponds to the value that was given, or to default if no matching value is found. The execution starts there, and continues, even if they’re under another label, until it reaches a break statement. In the example above you see that when an apple is green it will log out 'A yellow apple.' as well. This can sometimes bring more harm than good. So, remember to add your breaks!

Summary

This has been a quick rundown of the concept of control flow and conditional execution. You've learned about the if statement, how to create multiple routes your code can take and how to chain if-else statements. You now also know what the switch statement does and how to use it.

The concept of conditionals can be viewed as a set of parallel time-lines. They co-exist, but you can only exist in one, there's a path you must choose to proceed down the river of time.

Hope you guys and girls has as much fun reading this as I had writing it. Next time I'll be writing about loops.

Until next time, have fun!


Check out previous lessons


Drop an upvote if you liked the article, share if you believe it will be of help to someone. Feel free to ask any questions you have in the comments below.

Sort:  

Long time no see, dear bosnian friend!! See u around!

Have been a bit busy. Hope to focus more on Steemit in the coming months. :)

Congratulations @adnanrahic! You have received a personal award!

1 Year on Steemit
Click on the badge to view your Board of Honor.

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Congratulations @adnanrahic! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.033
BTC 64420.25
ETH 3150.23
USDT 1.00
SBD 3.99