Working with conditions and loops in JavaScript

If Statement

The most fundamental of the conditional statements is the if statement. An if statement will evaluate whether a statement is true or false, and only run if the statement returns true. The code block will be ignored in the case of a false result, and the program will skip to the next section.

An if statement is written with the if keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets. In short, it can be written as if () {}.

Here is a longer examination of the basic if statement.

if (condition) {
    // code that will execute if condition is true
}

The contents of an if statement are indented, and the curly brackets containing the block of code to run do not end in a semicolon, just like a function block.

As an example, let’s consider a shopping app. Say, for the functionality of this app, a user who has deposited a certain amount of funds into their account would then like to buy an item from the store.

shop.js
// Set balance and price of item
const balance = 500;
const jeans = 40;

// Check if there are enough funds to purchase item
if (jeans <= balance) {
  console.log("You have enough money to purchase the item!");
}
Output
You have enough money to purchase the item!

We have an account balance of 500, and want to buy a pair of jeans for 40. Using the less than or equal to operator, we can check if the price of jeans is less than or equal to the amount of funds we have. Since jeans <= balance evaluates to true, the condition will pass and the block of code will run.

In a new example, we will create a new shop item that costs more than the available balance.

shop.js
// Set balance and price of item
const balance = 500;
const phone = 600;

// Check if there is enough funds to purchase item
if (phone <= balance) {
    console.log("You have enough money to purchase the item!");
}

This example will have no output, since phone <= balance evaluates to false. The code block will simply be ignored, and the program will proceed to the next line.

Else Statement

With if statements, we only execute code when a statement evaluates to true, but often we will want something else to happen if the condition fails.

For example, we might want to display a message telling the user which fields were filled out correctly if a form did not submit properly. In this case, we would utilize the else statement, which is the code that will execute if the original condition does not succeed.

The else statement is written after the if statement, and it has no condition in parentheses. Here is the syntax for a basic if...else statement.

if (condition) {
    // code that will execute if condition is true
} else {
    // code that will execute if condition is false
}

Using the same example as above, we can add a message to display if the funds in the account are too low.

shop.js
// Set balance and price of item
const balance = 500;
const phone = 600;

// Check if there is enough funds to purchase item
if (phone <= balance) {
    console.log("You have enough money to purchase the item!");
} else {
    console.log("You do not have enough money in your account to purchase this item.");
}
Output
You do not have enough money in your account to purchase this item.

Since the if condition did not succeed, the code moves on to what’s in the else statement.


Else if Statement

With if and else, we can run blocks of code depending on whether a condition is true or false. However, sometimes we might have multiple possible conditions and outputs, and need more than simply two options. One way to do this is with the else if statement, which can evaluate more than two possible outcomes.

Here is a basic example of a block of code that contains an if statement, multiple else if statements, and an else statement in case none of the conditions evaluated to true.

if (condition a) {
    // code that will execute if condition a is true
} else if (condition b) {
    // code that will execute if condition b is true
} else if (condition c) {
    // code that will execute if condition c is true
} else {
    // code that will execute if all above conditions are false
}

JavaScript will attempt to run all the statements in order, and if none of them are successful, it will default to the else block.

You can have as many else if statements as necessary. In the case of many else if statements, the switch statement might be preferred for readability.

As an example of multiple else if statements, we can create a grading app that will output a letter grade based on a score out of 100.

The requirements of this app are as follows:

  • Grade of 90 and above is an A
  • Grade of 80 to 89 is a B
  • Grade of 70 to 79 is a C
  • Grade of 60 to 69 is a D
  • Grade of 59 or below is an F

Below we will create a simple set of ifelse, and else if statements, and test them against a given grade.

grades.js
// Set the current grade of the student
let grade = 87;

// Check if grade is an A, B, C, D, or F
if (grade >= 90) {
  console.log("A");
} else if (grade >= 80) {
  console.log("B");
} else if (grade >= 70) {
  console.log("C");
} else if (grade >= 60) {
  console.log("D");
} else {
  console.log("F");
}
Output
B

In our example, we first check for the highest score, which will be greater than or equal to 90. After that, the else if statements will check for greater than 8070, and 60 until it reaches the default else of a failing grade.

Although our grade value of 87 is technically also true for CD and F, the statements will stop at the first one that is successful. Therefore, we get an output of B, which is the first match.


Combining Conditions 

  • condition A  AND  Conditon B  if true combinely , with AND, all must return True
  • ConDtion  A OR condition B OR condition C ,with OR whole condition return true if any subconditions return true.

Falsy and truthy value

  • Javascript conditions with Boolean value(true or false)
  • for eg :
         const nameInput = 'max'
        if(nameinput === 'max')
          {
          // executes block of code
          }  
Note : yields true i.e a boolean value  
  •   Boolean(0) >> false
  • Boolean (" ") >> false 
  • null , undefined , NAN  >> false 
  • any non-empty string  >>false
  • all object and any other num including negative numbers are true >> True        

Concepts to be known in javascript
const nameInput = 'max'

        if(nameinput) // here yields a string not a boolean , so javascript tries to coarce if required.
          {
          // executes block of code
          } 


Ternary Operator

The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement.

A ternary operator is written with the syntax of a question mark (?) followed by a colon (:), as demonstrated below.

(condition) ? expression on true : expression on false

In the above statement, the condition is written first, followed by a ?. The first expression will execute on true, and the second expression will execute on false. It is very similar to an if...else statement, with more compact syntax.

In this example, we will create a program that checks if a user is 21 or older. If they are, it will print "You may enter" to the console. If they are not, it will print "You may not enter." to the console.

age.js
// Set age of user
let age = 20;

// Place result of ternary operation in a variable
const oldEnough = (age >= 21) ? "You may enter." : "You may not enter.";

// Print output
oldEnough;
Output
'You may not enter.'

Since the age of the user was less than 21, the fail message was output to the console. The if...else equivalent to this would be "You may enter." in the if statement, and "You may not enter." in the else statement.

addition to if...else, JavaScript has a feature known as a switch statement. switch is a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases. The switch statement is closely related to a conditional statement containing many else if blocks, and they can often be used interchangeably.

In this tutorial, we will learn how to use the switch statement, as well as how to use the related keywords casebreak, and default. Finally, we’ll go through how to use multiple cases in a switch statement.

Switch

The switch statement evaluates an expression and executes code as a result of a matching case. At first it can look a bit intimidating, but the basic syntax is similar to that of an if statement. It will always be written with switch () {}, with parentheses containing the expression to test, and curly brackets containing the potential code to execute.

Below is an example of a switch statement with two case statements, and a fallback known as default.

switch (expression) {
    case x:
        // execute case x code block
        break;
    case y:
        // execute case y code block
        break;
    default:
        // execute default code block
}

Following the logic of the code block above, this is the sequence of events that will take place.

  • The expression is evaluated
  • The first casex, will be tested against the expression. If it matches, the code will execute, and the break keyword will end the switch block.
  • If it does not match, x will be skipped and the y case will be tested against the expression. If y matches the expression, the code will execute and exit out of the switch block.
  • If none of the cases match, the default code block will run.

Let’s make a working example of a switch statement following the syntax above. In this code block, we will find the current day of the week with the new Date() method, and getDay() to print a number corresponding to the current day. 1 stands for Monday, all the way through 7 which stands for Sunday. We’ll start by setting up our variable.

const day = new Date().getDay();

Using switch, we will send a message to the console each day of the week. The program will run in order from top to bottom looking for a match, and once one is found, the break command will halt the switch block from continuing to evaluate statements.

week.js
// Set the current day of the week to a variable, with 1 being Monday and 7 being Sunday
const day = new Date().getDay();

switch (day) {
    case 1:
        console.log("Happy Monday!");
        break;
    case 2:
        console.log("It's Tuesday. You got this!");
        break;
    case 3:
        console.log("Hump day already!");
        break;
    case 4:
        console.log("Just one more day 'til the weekend!");
        break;
    case 5:
        console.log("Happy Friday!");
        break;
    case 6:
        console.log("Have a wonderful Saturday!");
        break;
    case 7:
        console.log("It's Sunday, time to relax!");
        break;
    default:
        console.log("Something went horribly wrong...");
}
Output
'Just one more day 'til the weekend!'

This code was tested on a Thursday, which corresponds to 4, therefore the console output was Just one more day 'til the weekend!. Depending on what day of the week you are testing the code, your output will be different. We have included a default block at the end to run in case of an error, which in this case should not happen as there are only 7 days of the week. We also could have, for example, only printed results for Monday to Friday, and the default block could have had the same message for the weekend.

If we had omitted the break keyword in each statement, none of the other case statements would have evaluated to true, but the program would have continued to check until it reached the end. In order to make our programs faster and more efficient, we include the break.

Switch Ranges

There might be an occasion in which you will need to evaluate a range of values in a switch block, as opposed to a single value as in our example above. We can do this by setting our expression to true and doing an operation within each case statement.

To make this easier to understand, we will use a familiar example. In the conditional statements tutorial, we made a simple grading app which would take a number score and convert it to a letter grade, with the following requirements.

  • Grade of 90 and above is an A
  • Grade of 80 to 89 is a B
  • Grade of 70 to 79 is a C
  • Grade of 60 to 69 is a D
  • Grade of 59 or below is an F

Now we can write that as a switch statement. Since we’re checking a range, we will perform the operation in each case to check if each expression is evaluating to true then break out of the statement once the requirements for true have been satisfied.

grades.js
// Set the student's grade
const grade = 87;

switch (true) {
    // If score is 90 or greater
    case grade >= 90:
        console.log("A");
        break;
    // If score is 80 or greater
    case grade >= 80:
        console.log("B");
        break;
    // If score is 70 or greater
    case grade >= 70:
        console.log("C");
        break;
    // If score is 60 or greater
    case grade >= 60:
        console.log("D");
        break;
    // Anything 59 or below is failing
    default:
        console.log("F");
}
Output
'B'

The expression in parentheses to be evaluated is true in this example. This means that any case that evaluates to true will be a match.

Just like with else ifswitch is evaluated from top to bottom, and the first true match will be accepted. Therefore, even though our grade variable is 87 and therefore evaluates to true for C and D as well, the first match is B, which will be the output.

Multiple Cases

You may encounter code in which multiple cases should have the same output. In order to accomplish this, you can use more than one case for each block of code.

In order to test this, we are going to make a small application matching the current month to the appropriate season. First, we will use the new Date() method to find a number corresponding to the current month, and apply that to the month variable.

const month = new Date().getMonth();

The new Date().getMonth() method will output a number from 0 to 11, with 0 being January and 11 being December. At the time of this publication, the month is September, which will correspond to 8.

Our application will output the four seasons with the following specifications for simplicity:

  • Winter: January, February, and March
  • Spring: April, May, and June
  • Summer: July, August, and September
  • Autumn: October, November, and December

Below is our code.

seasons.js
// Get number corresponding to the current month, with 0 being January and 11 being December
const month = new Date().getMonth();

switch (month) {
    // January, February, March
    case 0:
    case 1:
    case 2:
        console.log("Winter");
        break;
    // April, May, June
    case 3:
    case 4:
    case 5:
        console.log("Spring");
        break;
    // July, August, September
    case 6:
    case 7:
    case 8:
        console.log("Summer");
        break;
    // October, November, December
    case 9:
    case 10:
    case 11:
        console.log("Autumn");
        break;
    default:
        console.log("Something went wrong.");
}

When we run the code, we’ll receive output identifying the current season based on the specifications above.

Output
Summer

The current month at the time of publication was 8, which corresponded to one of the case statements with the "Summer" season output.


Introduction

Automation is the technique of making a system operate automatically; in programming, we use loops to automate repetitious tasks. Loops are one of the most useful features of programming languages, and in this article we will learn about the while and do...while loops in JavaScript.

The while and do...while statements in JavaScript are similar to conditional statements, which are blocks of code that will execute if a specified condition results in true. Unlike an if statement, which only evaluates once, a loop will run multiple times until the condition no longer evaluates to true.

Another common type of loop you will encounter is the for statement, which executes a set number of times. while and do...while loops are conditionally based, and therefore it is not necessary to know beforehand how many times the loop will run.

While Loop

In JavaScript, a while statement is a loop that executes as long as the specified condition evaluates to true.

The syntax is very similar to an if statement, as seen below.

while (condition) {
    // execute code as long as condition is true
}

The while statement is the most basic loop to construct in JavaScript.

As an example, let’s say we have an aquarium that has a population limit. For each iteration of the loop, we will add one fish. Once the aquarium has 10 fish, the population limit will be reached, and the program will cease to add more fish.

aquarium.js
// Set population limit of aquarium to 10
const popLimit = 10;

// Start off with 0 fish
let fish = 0;

// Initiate while loop to run until fish reaches population limit
while (fish < popLimit) {
    // add one fish for each iteration
    fish++;
    console.log("There's room for " + (popLimit - fish) + " more fish.");
}

Once we run the above program, we’ll receive the following output, showing the iteration of the program through the while loop until the conditions are no longer evaluated as true.

Output
There's room for 9 more fish. There's room for 8 more fish. There's room for 7 more fish. There's room for 6 more fish. There's room for 5 more fish. There's room for 4 more fish. There's room for 3 more fish. There's room for 2 more fish. There's room for 1 more fish. There's room for 0 more fish.

In our example, we set our while loop to run as long as the number of fish was less than the population limit of the aquarium. For each iteration, one fish is added to the aquarium until all 10 spots are filled. At that point, the loop stops running.


We already learned about the while loop, which executes a block of code for as long as a specified condition is true. Building on that is the do...while statement, which is very similar to while with the major difference being that a do...while loop will always execute once, even if the condition is never true.

Below we will demonstrate the syntax of the do...while loop.

do {
    // execute code
} while (condition);

As you can see, the do portion of the loop comes first, and is followed by while (condition). The code block will run, then the condition will be tested as it is in a normal while loop.

To test this, we can set a variable to 0, increment it inside the do statement, and set our condition to false.

falseCondition.js
// Set variable to 0
let x = 0;

do {
    // Increment variable by 1
    x++;
    console.log(x);
} while (false);
Output
1

Our output came out to 1, meaning that the code block iterated through the loop once (from 0) before it was stopped by an unsuccessful while condition.

While keeping in mind that the loop will iterate at least once, the do...while loop can be used for the same purposes as a while loop.




Comments

Popular posts from this blog

JavaScript — Double Equals vs. Triple Equals - weird things on JavaScript

06_Understanding Execution Context and Execution Stack in Javascript

Creating and inserting element- part-2