7. Adding Logic

Objective: By the end of this checkpoint, you will be able to add conditional logic to your code.

Key Terms

  • Application Logic
  • While Loop
  • Do…While Loop
  • For Loop
  • For…In Loop
  • For…Of Loop
  • JavaScript Conditions
  • if statement
  • if…else statement
  • if…else if… statement
  • switch case statement
  • break statement

Loops in JavaScript

Loops are useful when you have to execute the same lines of code repeatedly, for a specific number of times or as long as a specific condition is true. The basic idea behind a loop is to automate the repetitive tasks within a program to save time and effort. JavaScript now supports five different types of loops:

  • while — loops through a block of code as long as the condition specified evaluates to true.
  • do…while — loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true.
  • for — loops through a block of code until the counter reaches a specified number.
  • for…in — loops through the properties of an object.
  • for…of — loops over iterable objects such as arrays, strings, etc.

In the following sections, we will discuss each of these loop statements in detail.

 

The While Loop

This is the simplest looping statement provided by JavaScript.

The while loop loops through a block of code as long as the specified condition evaluates to true. As soon as the condition fails, the loop is stopped. The generic syntax of the while loop is:

The following example defines a loop that will continue to run as long as the variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

Try to run this code in Repl.it:

Note: Make sure that the condition specified in your loop eventually goes false. Otherwise, the loop will never stop iterating which is known as an infinite loop. A common mistake is to forget to increment the counter variable (variable i in our case).

 

The Do…While Loop

The do-while loop is a variant of the while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop, the block of code executes once and then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition evaluated to holds true. The generic syntax of the do-while loop is:

The JavaScript code in the following example defines a loop that starts with i=1. It will then print the output and increase the value of variable i by 1. After that, the condition is evaluated and the loop will continue to run as long as the variable i is less than, or equal to, 5.

Try to run this code in Repl.it:

 

Difference Between While and Do…While Loop

The while loop differs from the do-while loop in one important way — with a while loop, the condition to be evaluated is tested at the beginning of each loop iteration. So if the conditional expression evaluates to false, the loop will never be executed.

With a do-while loop, on the other hand, the loop will always be executed once even if the conditional expression evaluates to false. This is because, unlike the while loop, the condition is evaluated at the end of the loop iteration rather than the beginning.

 

The For Loop

The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for a certain number of times. Its syntax is:

The parameters of the for loop statement have the following meanings:

  • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
  • condition — it is evaluated at the beginning of each iteration. If it evaluates to true, the loop statements execute. If it evaluates to false, the execution of the loop ends.
  • increment — it updates the loop counter with a new value each time the loop runs.

The following example defines a loop that starts with i=1. The loop will continue until the value of variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

Try to run this code in Repl.it:

The for loop is particularly useful for iterating over an array. The following example will show you how to print each item or element of the Array.

Try to run this code in Repl.it:

 

The For…In Loop

The for-in loop is a special type of loop that iterates over the properties of an Object, or the elements of an array. The generic syntax of the for-in loop is:

The loop counter (i.e., variable) in the for-in loop is a string, not a number. It contains the name of the current property or the index of the current array element.

The following example will show you how to loop through all properties of a JavaScript object.

Similarly, you can loop through the elements of an array.

Try to run this code in Repl.it:

Note: The for-in loop should not be used to iterate over an array where the index order is important. You would be better off using a for loop with a numeric index.

 

The For…Of Loop

ES6 introduces a new for-of loop which allows us to iterate over arrays or other iterable objects (e.g., Strings) very easily. Also, the code inside the loop is executed for each element of the iterable object.

The following example will show you how to loop through arrays and strings using this loop.

Try to run this code in Repl.it:

Note: The for...of loop doesn’t work with objects because they are not iterable. If you want to iterate over the properties of an object, you can use the for-in loop.

 

JavaScript Conditions

While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make the correct decisions and perform the right actions.

JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement.

 

FlowChart of if-else

The following flow chart shows how the if-else statement works.

  • if statement
  • ..else statement
  • ..else if… statement

 

if statement

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

The syntax for a basic statement is the following:

Here, a JavaScript expression is evaluated. If the resulting value is true, then the given statement(s) are executed. If the expression is false, then no statement would be executed. Most of the time, you will use comparison operators while making decisions.

Try to run the following example in Repl.it:

 

if…else statement

The if...else statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way. Here is the syntax:

Here, once again, the JavaScript expression is evaluated. If the resulting value is true, then the given statement(s) in the if block are executed. If the expression is false, then the given statement(s) in the else block is executed.

Try to run the following code in Repl.it:

if…else if… statement

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.

The syntax for an if-else-if statement is the following:

There is nothing special about this code. It is just a series of if statements, where each if statement is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions are true, then the else block is executed.

Try to run the following code in Repl.it:

 

switch case statement

You can use multiple if...else...if statements seen in the chapter above to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.

Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation and it does it in a more efficient way than with a repeated if...else...if statement.

Flow Chart for Switch Case Statement

The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, then a default condition will be used.

The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.

Try to run the following example in Repl.it:

break statements play a major role in switch case statements.

To realize the importance of break statements, run the code in this Repl.it that uses switch case statements without any break statements: