DEV Community

Cover image for JavaScript: Control Flows and Conditional Programming
Dwaipayan C(Dtech-Dbug)
Dwaipayan C(Dtech-Dbug)

Posted on

JavaScript: Control Flows and Conditional Programming

Control Flow

If a program contains more than one statement - they are executed in an order. The order of execution is in such a way that it tells a story, from top to bottom.

Consider the below snippet :

let myName = "Dtech-Dbug";

console.log("My Name is :" + myName);
//o/p : My Name is :Dtech-Dbug
Enter fullscreen mode Exit fullscreen mode

The above snippet, although hard-coded, really tells a story :

  • First we define a variable named myName
  • Then we print that in the console.

Note : Console.log() is a native binding in JavaScript, a function more specifically. All it does is print anything you pass in between the parenthesis onto the console.

A rather simple schematic representation of the above code block would be a top-down arrow.

Conditional Flows

Not all the time will programs be super simple and a straight and simple top down arrow.
There can(and WILL) very well be cases where the program needs to be branched and the execution needs to follow a certain branch based on the current situation at hand.

Let us consider a real world scenario where branching and execution based on branching occurs.

Imagine this is 2014 and you are excited to watch the FIFA WC final between Argentina and Germany. You are a supporter of Argentina and decided that if Argentina wins then you would drink a beer to celebrate.

If we transform the above paragraph into pseudo-codes it will pretty simply look like:


if(Argentina)
{
Drink a beer to celebrate all night;
}

Enter fullscreen mode Exit fullscreen mode

Now, this is not actual code. This is a pseudo-code.

Pseudo-Code : are text based details that help in designing algorithms or code.

Pseudo-Codes can be very easily be converted into actual codes, as you can guess, by the looks of the above snippet.

Back to the snippet of pseudo-code. While the pseudo-code talks about the situation that might follow the win of Argentina, it does not say anything about any other possibilities or occurrence.

Now, if you remember the final game that year, Argentina did not make it. 😭😭 Because Germany Scored at 113' and bagged the WC. :')

You were prepared for only if Argentina wins and that did not quite happen. You clearly missed out to think the opposite case i.e, what happens when Argentina does not win! So, what now?

Well it turns out in programming(and in real world) - the onus is on the programmer to design an algorithm or code that is self defensive by handling the various cases that may occur.

With that being mentioned, the previous snippet can be reworked to look like:


if(Argentina)
{
Drink a beer to celebrate all night;
}

if(Germany)
{
Drink three beers to forget the pain and sleep;
}

Enter fullscreen mode Exit fullscreen mode

Now the program or the pseudo-code more precisely, is quite self-defensive as it is handling another possibility.

It turns out in a crucial game like the FIFA WC - a match between two teams, say A and B, can really have one of two possibilities. Either A wins or B wins, neglecting any other factors that might cause the game to stop like natural causes.

With this information at our disposal we can further modify the pseudo-code by thinking like, there can only be two situations in the final:

  • either Argentina wins
  • or Argentina does not win - i.e, Germany wins

With this informal language, we can re-design the pseudo-code to look like:


// the situation when Argentina Wins
if(Argentina)
{
Drink a beer to celebrate all night;
}

// the situation when Argentina does not win i.e, Germany wins
else
{
    Drink three beers to forget the pain and sleep;
}

Enter fullscreen mode Exit fullscreen mode

Code It Yourself (CIY)

Imagine a problem statement where you are to categorize a number within the categories: Even, Prime, Odd, Even-Prime and print the categories onto the console.

If you remember your numbers,

  • Even numbers are numbers completely divisible by 2 - i.e, leaves 0 as remainder.
  • Prime numbers are numbers which are only divisible by itself and 1.
  • Odd numbers are numbers which are not even - i.e, they are not completely divisible by 2.
  • Even Prime numbers are numbers which have feats of both Even numbers and Prime numbers. There exists only one such number and that is 2.

Now, how shall we go about the problem and write a code that solves the given problem statement?

A little bit of interruption here - I would highly encourage you to try to start forming the pseudo-codes yourself and refer here if you are stuck. If you are very new to programming or JavaScript please stick by, sorry for the interruption.

Forming the Pseudo-Code

// if number is 0
if(number is equal to 0)
{
 console.log('Not a natural number')
}

// if number is 2, it is even-prime
if(number is equal to 2)
{
    console.log('Even Prime Number');
}

// check for prime
if(number % 1 is equal to 0 and number % number is equal to 0)
{
    console.log('Prime Number');
}

else
{
    // check for even
    if (number % 2 is equal to 0)
    {
        console.log('Even Number');
    }

    // check for odd
    else
    {
        console.log('Odd Number');
    }


}

Enter fullscreen mode Exit fullscreen mode

Pretty verbose as it is but this is the pseudo-code that covers all the instances.
And it follows a specific branch of execution for different values of the number - that is mentioned repeatedly in the pseudo-code.
The actual code can be very well transformed from this snippet itself.

Points to note

  • we are preemptively checking for the case where the number can be 0. Bc, technically there is no reason not for that occurrence. And it is always a good idea to think and handle all the edge cases and make the program more self-defensive.

  • the % operator is called the modulo operator. It is an arithmetic operator that quite simply returns the remainder of integer divisions. So the expression 4 % 2 basically returns the remainder value after dividing 4 by 2 - which is 0. Therefore, all even numbers have 0 as remainders when divided by 2.

  • while using conditionals, there can be a lot of branches and you can use nested conditionals. Nested conditionals is a fancy term meaning using conditionals inside conditionals. Notice the if-else blocks inside the first else block. That is nested conditional so
    to speak.

There you have your first take home assignment - transform the pseudo-code into actual code and share it on Twitter or Linkedin and tag me, if you will! 🤗🥰

Wrapping Up

  • Execution of statements in a program occurs in a specific flow which essentially tells a story - a story that the programmer wrote and asked the machine to decipher. 📕

  • Not all programs are easy and just a straight road. 🦕

  • More than many programs are branched and the execution follows a certain situation at hand.These kind of execution is called conditional execution. And the statements which represent conditional execution are typically in the form of if(p) then q and they called conditional statements/sentences. 🦦

  • In the form if(p) then q; p is more mathematically referred to as the hypothesis of the conditional and q is called the conclusion of the conditional. From our FIFA WC example above: Drinking beer and celebrating all night was a conclusion to the hypothesis if Argentina Wins. 🍺

  • The onus is on us programmers to make the program as self defensive as possible by handling not just one obvious case but other cases as well. Analogous to the form 👇

if(p) then q;

if(r) then s;

else t;
Enter fullscreen mode Exit fullscreen mode
  • The control only enters a block if the hypothesis is true. Consider the below snippet 🐳
let x = 2;

if (x === 3) {
  // x === 3 is hypothesis
  // hypothesis is false; since we declared x to be 2
  // this if block is skipped totally
  console.log("x is three");
}

// control comes down to this else block
else {
  console.log("x is not three");
}

// output : x is not three
Enter fullscreen mode Exit fullscreen mode

Conclusion

  • If you are new to programming, consider solving the above assignment and tag me on twitter/linkedin w/ the end code. 🤝
  • If you found this article a good read consider leaving a reaction or sharing the article w/ your friends who share similar interests. Comment below if you don't get something and I would be happy to cooperate. 🧙‍♂️

Wanna talk about tech, life or even share a song suggestion?
Find me here 🧙‍♂️

Relevant Hyperlinks

Top comments (0)