JavaScript Conditions & Loops (Part-2)

Conditional statements in JavaScript allow you to make decisions in your code based on certain conditions or Conditional statements are used to perform different actions based on different conditions. These statements help control the flow of your program by executing different blocks of code depending on whether a specified condition evaluates to true or false. The main conditional statements in JavaScript are:

  1. if statement: The if statement is the most basic conditional statement. It evaluates a given condition and executes a block of code if the condition is true.

  2. if-else statement: The if-else statement extends the basic if statement by allowing you to provide an alternative block of code that gets executed when the condition is false.

  3. if-else if-else statement: You can use the else if construct to test multiple conditions in sequence and execute different blocks of code based on the first condition that evaluates to true.

The Conditional flow example:

Now let's try to implement it in our code:

Example no.1 :

Example no.2 :

What is prompt: The JavaScript window. prompt() is a built-in function that is used to display a dialog box that asks the user to input some text. This pop-up box will appear and takes user input before entering the web page. It waits until the user enters any value in the text box or we can also cancel the dialog box.

  1. switch statement: The switch statement is used to perform different actions based on different conditions.

In this example, the user is prompted to enter a fruit name, and the switch statement identifies various fruits based on their names. The case "grape": and case "grapes": lines demonstrate how you can handle multiple cases with the same response.

These are the basic conditional statements in JavaScript. Additionally, you can use logical operators (&&, ||, !) to combine conditions and create more complex decision-making structures. It's important to pay attention to the order of your conditions and the logical operators to ensure your code behaves as intended.

Loops in Javascript:

Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below:

Iterative Method: The iterative method to do this is to write the console.log() statement 10 times.

console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");

Using Loops: In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below:

for (let i = 0; i < 10; i++) {
    console.log("Hello World");
}

Many things may seem confusing to you in the above program at this point but do not worry you will be able to understand everything about loops in JavaScript by the end of this tutorial. You can observe that in the above program using loops, we have used the console.log statement only once but still, the output of the program will be the same as that of the iterative program where we have used the console.log statement 10 times. In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.

  • An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.

  • Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeats it.

  • Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop.

There are mainly two types of loops:

  • Entry Controlled Loop: In these types of loops, the test condition is tested before entering the loop body. The for Loop and while Loop are entry-controlled loops.

  • Exit Controlled Loop: In these types of loops the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. The do-while loop is exit controlled loop.

JavaScript mainly provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time. Let us learn about each one of these in detail.

while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

Syntax :

while (boolean condition) {
    loop statements...
}

Flowchart:

while loop

  • While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loop

  • Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an updated value for the variable being processed for the next iteration.

  • When the condition becomes false, the loop terminates which marks the end of its life cycle.

for loop: for loop provides a concise way of writing the loop structure. Unlike while loop, a for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping.

Syntax:

for (initialization; testing condition; increment/decrement) {
    statement(s)
}

Flowchart:

  • Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.

  • Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.

  • Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.

  • Increment/ Decrement: It is used for updating the variable for the next iteration.

  • Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.

do-while: The do-while loop is similar to the while loop with the only difference is that it checks for the condition after executing the statements, and therefore is an example of an Exit Control Loop.

Syntax:

do {
    Statements..
}
while (condition);

Flowchart:

do-while

  • The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.

  • After the execution of the statements and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.

  • When the condition becomes false, the loop terminates which marks the end of its life cycle.

  • It is important to note that the do-while loop will execute its statements at least once before any condition is checked and therefore is an example of the exit control loop.

Infinite loop: One of the most common mistakes while implementing any sort of looping is that it may not ever exit, i.e. the loop runs for infinite times. This happens when the condition fails for some reason.

Example: This example shows an infinite loop.

  1. Using a for loop:
// Infinite loop because condition is not false
// condition should have been i > 0.
for (let i = 0; i < 10)  {
    console.log("Crashing the loop");
}
  1. Using a while loop:
let x = 5;

// Infinite loop because update statement
// is not provided
while (x == 5) {
    console.log("In the loop");
}

Here are some more loops used in Javascript these days:

For-in: For-in loop in JavaScript is used to iterate over the properties of an object. The for-in loop iterates only over those keys of an object which have their enumerable property set to “true”.

examples to solve

for loop :

//table of 5
for(var i = 5; i < 51; i= i+5){
    console.log(i)
}
  •   //find the odd number
      for (var i = 0; i<10; i++){
         if(i%2 != 0)
         console.log(i)
      }
    
//find the even number
for (var i = 0; i<10; i++){
   if(i%2 == 0)
   console.log(i)
}

While loop :

var i = 0;
while (i < 0) {
  console.log("I'm while Loop");
  i++;
}

do while loop :

var j = 0;
do {
  console.log("I'm do while loop");
  j++;
} while (j < 10);

for in :

var animal = {
   name: "Tiger",
   leg: 4,
   age: 11,
}
for (var key in animal ){
console.log(key)
}