Choices in JS

#teamtanayejschallenge- Part 3- Conditional Statements and Loops in JavaScript

Sudesh Kumar Das
5 min readDec 5, 2020
Photo by James Harrison on Unsplash

Humans are all about choices. From choosing what to wear to your best freind’s birthday to choosing where & what to eat at dinner today. This, the creators of all programming languages knew. As such, JavaScript has various options to write codes which works on the very principle of Choices

Straight Line Flow Control

Consider the following code

var name = prompt('What is your name?');
var greet = 'Good Morning, ' + name;
console.log(greet);
/* the above code snippet asks the user for the name, and greets Good Morning.*/

This code is a straight line flow control. The next line of code is executed only when the previous one has been executed. There is no choice of which code to execute.

Imagine if the time of the day was evening, wouldn’t it be weird to be greeted with ‘Good Morning! Dash’ ? That’s where we need to act on choices.

Conditional Statements

Conditional statements are executed based on the condition provided. There are 2 types of conditional statements-

  • if- else statement
  • switch- case statement

if- else statement

var name = prompt('What is your name?');if (timeOfDay == 'morning') {
greet = 'Good Morning! ' + name;
} else if (timeOfDay == 'evening') {
greet = 'Good Afternoon! ' + name;
} else {
greet = 'Hello! ' + name;
}
console.log(greet);/* this code will ask for the user's name, check the time of the day in the system and greet accordingly. */

What essentially if-else statements means is that one block of code is executed if, and only if the condition is true, otherwise another block of code is executed.

Here’s the syntax for ‘if-else’ statements

if (condition) {
statement1;
} else if (condition) {
statement2;
} else {
statement2;
}
/* note:- 'else-if' part is not compulsory, if there are only 2 choices. Likewise, 'else' will be redundant if there is no choice for falsity. */

switch-case statement

Switch case statement comes from programming customs of other languages such as Java and Python. Neither widely used nor much dynamic, switch-case statements can only compare with equality.

Here’s the syntax

switch(case) {
case 1: statement1; break;
case 2: statement2; break;
case 3: statement3; break;
case 4: statement4; break;
default: statement;
}
/* the switch-case takes a variable and compare with the cases, if equal, executes the statement, otherwise skip. *// break essentially tells to come out of the block of code

Here’s a simple use of switch case, relating to real life example

switch(season) {
case 'Rainy':
case 'Winter':
case 'Spring': doNotEatIceCrean; break;
case 'Summer': iceCreamTime; break;
default: justTasteIceicream ;
}
/* easy enough to understand. If it is any season other than summer, do no eat ice-cream, you'll get sick. Summer it is? Enjoy your ice-cream. Don't know what season it is? You can have one scoop. */

Loopity loop

Ever wondered how the newspaper is there in front of your door step? Or how the milkman provides milk for your daily coffee? Read on to understand.

Consider loops as circle, their is no end, unless you draw a line to break that circle. Loops in JavaScript keep on executing a block of code until a condition is being fulfilled.

There are three types of loops in JavaScript-

  • while loop
  • do-while loop
  • for loop

while loop

You live with your family, happily, sipping tea or coffee, three times a day. The milkman knocks every morning and hands over your nutritious milk. But, how did it even start to happen? He was not coming before you moved in to this awesome flat.

Here’s how it came into existence-

while(iLiveHere) {
supplyMilkTomorrow;
startNextDay;
}
/* as long as you are living in that flat, the milkman will knock everyday with the rise of the sun every morning. */

‘while’ loop executes a block of code as long as the condition is true, which is checked on entry, everytime the loop starts from the beginning.

do-while loop

But hey, lets go back to the day you moved here. Oh, the fatigue of moving furniture. Phew, I’m glad you’re settled now. The very first time you enquired about the milkman, I’m sure you checked the quality of the milk. No one wants to drink white water (more water mixed than milk). And at any point of time of your stay here, should the milk be of poor quality, you would stop buying the milk from him.

do {
supplyMilkTomorrow;
startNextDay;
} while (milkQuality == good)
/* if the quality goes down anytime, the purchase will be stopped from the next day. *//* also, note that you buy the first time without checking the quality, meaning you will get the milk, at least once. */

As you see, the code will be executed at least once. That’s why ‘do-while’ loops are exit-control loops whereas ‘while’ loops are entry-control loops.

for loop

I hope you are healthy drinking milk everyday. ‘But Dash, you forgot about the payment.’ Don’t worry, my friend, I got you covered. If you are living under the rock, letting your special one to deal with the household bills, its high time to share some of that load. The milkmen take payment every month. Meaning, you buy milk for each month, not each day.

for(startMonth; livingHere; nextMonth) {
makePayment;
}
/* it seems tricky, but easy to understand going step by step. The first step is startMonth, that is the initialisation of the variable which will tell which month to start from to provide for milk. *//* the next code snippet in the bracket is livingHere, it is the condition for loop, as long as you are living there, the milk should be at your door *//*the last part is nextMonth, which is updating the month, so that we can make payment only when the next month arrive. */

‘for’ loops execute the block of code as long as the condition is true. It is similar to while loop, the only difference being that the initialisation of the variable takes place outside the loop strictly in while-loop, whereas the same can be done inside the parenthesis in for loop.

Here are the syntaxes of all the three loops

// while-loopinitialisation;
while(condition) {
statement;
update expression;
}
// do-while loopinitialisation;
do {
statement;
update expression;
} while(condition)

// for loop
for(initialisation; condition; update expression;) {
statement;
}

So, we learnt about different types of loops, conditional statements and understood how milk comes to your house.

Final thoughts- Keep sipping your awesome tea. Or coffee, if you are a coder. PS- Coders love coffee.

That is it, for details of the challenge. Click Here. This article was inspired by Eloquent JavaScript- Chapter 2 by Marijn Haverbeke. Happy Coding! (:

--

--