Categories
JavaScript JavaScript Basics

Controlling Your JavaScript Program’s Workflow With Loops and Branches

Spread the love

Conditional Statements

Conditional statements allow our code to run differently depending on the conditions given.

For example, if we want to display “You are too young to drink” when age is less than 21, we can use a conditional statement to do this.

There are a few ways to conditionally run code in JavaScript. One is the if...else statement. If you have lots of cases, then you can use the switch statement to simplify your code.

If…Else

The if...else statement is a way to run code depending on what condition you pass into the condition of the if statement.

Whatever condition you pass into it has to evaluate to a Boolean expression, or it can be automatically converted into a Boolean.

The if statement can be used by itself, but the else statement must be used with the if statement. The else statement is used when you want to execute something when the if statement is false.

You can also write else if (condition) if you want to run something with the given condition, and you have multiple cases with different conditions.

To write an if...else statement, we write:

if (condition){
 // run code
}

We do this in the simplest cases, such as when we only want to run something if we have some condition.

If we want to run something different when thecondition is false, then we write:

if (condition){
 // run code
}
else {
 // run other code
}

If we have more than two cases, then we can use else if like so:

if (condition1){
 // run code
}
else if (condition2){
 // run different code
}
else {
 // run code when condition1 and condition2 are both false
}

But else if and else don’t always have to be optional.

If you want to log a message for drinkers given their age, we can write:

const age = 19;
if (age < 21){
  console.log('You are too young to drink');
}
else {
  console.log('You are old enough to drink');
}

In the code above, we log, “You are too young to drink” if age is less than 21. Since age is 19, which is less than 21, we log “You are too young to drink.” If age is set to 22, then we log “You are old enough to drink.”

If your if...else statement only has two cases, we can shorten it by writing:

condition ? a : b

Here, a and b are any piece of code you want to execute, but it should be used if a and b are short since it’s meant to be written in one line.

So for the example above, we can also write:

const age = 19;
console.log(age < 21 ? 'You are too young to drink' : 'You are old enough to drink');

If we want to write if statements with multiple cases, we write:

const score = 80;
if (score >= 80){
  console.log('You get an A');
}
else if (score >= 65 && score < 80){
  console.log('You get a B');
}
else if (score >= 50 && score < 65){
  console.log('You get a C');
}
else {
  console.log('You failed');
}

In the example above, we have multiple cases. We determine what to log based on the range of thescore.

If the score is 80 or higher, we log, “You get an A.” If thescore is higher than or equal to 65 and less than 80, we log, “You get an A.” If the score is higher than or equal to 50 and less than 65 we log, “You get an A.” Otherwise, we log, “You failed.”

Switch statement

The if...else statement above can also be rewritten with the switch statement. A switch statement can be written like so:

switch (expression) {
  case value1:
    // Statements
    break;
  case value2:
    // Statements
    break;
  case value3:
    // Statements
    break;
  default:
    // Statements
    break;
}

In the switch block above, if we have anexpression equal to value1, then the statements in that block are executed.

This rule also applies to the other blocks. It’s critical to have the break statement at the end of every case block so it won’t run the other case blocks once the correct block is run. The default block runs if the value given doesn’t match any value in the case block.

An example of a switch statement would be the following to log “Hello” given a language:

const language = "Spanish";
switch (language){
 case "English":
   console.log("Hello");
   break;
 case "Spanish":
   console.log("Hola");
   break;
 case "Portugese":
   console.log("Ola");
   break;
 case "French":
   console.log("Bonjour");
   break;
 default:
   console.log(`I don't speak ${language}`);
}

In this statement, we log a hello message if we set language to English, Spanish, Portuguese, or French. Otherwise, we log `I don’t speak ${language}`, where language is anything that’s not English, Spanish, Portuguese, or French.


<img class="do t u hm ak" src="https://miro.medium.com/max/12000/0*8hfiungQLRRSm5fM" width="6000" height="4000" role="presentation"/>

Photo by Tine Ivanič on Unsplash

Loops

Loops are for running repeated operations. We need them so we can avoid writing the same code too many times. They let us repeatedly run code until the ending condition is met.

In JavaScript, we have the for loop, the while loop, and the do...while loop.

For loop

The for loop has three parts.

There’s the initialization code, which lets us define how to begin the loop by setting a variable to some initial value.

They also have a condition that is evaluated in every iteration, and if the condition is true, the loop continues to execute.

Then there’s the third expression which is run after each iteration of the loop.

The three expressions aren’t required, but they’re almost always included. They’re usually used for repeatedly running code a determined number of times.

For example, with the for loop, given that we have the name array, we can traverse the loop by running:

let names = new Array('Bob','Jane', 'John');
for (let i = 0; i < names.length; i++){
  console.log(names[i]);
}

A for loop is usually written with the starting condition as the first statement, then the ending condition in the second statement, and the index changing condition in the third statement. The statements are separated by the semicolons. Because arrays start with index zero in JavaScript, we terminate the loop when the array’s index reaches one less than the array’s length.

In the example above, the steps for running the loop are:

  1. The variable i is set to 0 at the beginning of the loop
  2. names[i] is retrieved from the array and logged in the console
  3. i is incremented by 1, so i becomes 2
  4. The three steps above are repeated until i becomes 3, which is the value of names.length, and the loop ends because 3 < 3 is false.

For…in loop

The for...in loops lets us traverse the properties of an object.

For example, if we have this object …

let obj = {a: 1, b: 2, c: 3}

… then we can use the for...in loop to loop through the properties of this object by running:

for (let prop in obj){
  console.log(obj[prop]);
}

prop will contain the property name or keys of the object. So prop will be a, b, or c as the loop is running. In the loop above, we log the values given those keys by passing prop into the bracket of the obj object.

For…of loop

The for...of loop lets us loop through an iterable object like an array in a convenient manner. It eliminates the need for setting those conditions to traverse through the whole array as we did with the plain for loop.

For instance, if we want to use the for...of loop to traverse the names array we have above, then we write:

let names = new Array('Bob','Jane', 'John');
for (const name of names){
  console.log(name);
}

The name variable automatically gets an entry of the names variable as we run the loop — so first we log Bob, then we log Jane, then we log John.

Note that we used const since we didn’t have to do anything with the array entries, but we can also use let if we want do something to each entry.

For example, if we define nums by writinglet nums = [1,2,3], then we can add 1 to each entry of the array by writing:

let nums = [1,2,3];
for (let num of nums){
  num += 1;
  console.log(name);
}

By switching out const for let, then we can add 1 to each entry of nums. So we log 2, 3, and 4.

Other iterable objects that work with the for...of loop include maps, sets, strings, and TypedArray.

If we loop through a string, then we get the individual characters of the string in each iteration. For example, if we have …

const str = 'foo';

for (const char of str) {
  console.log(char);
}

… then we get f, o, and o in each iteration.

For TypedArrays, if we have …

const typedArray = new Uint8Array([0x00, 0x06]);

for (const value of typedArray) {
  console.log(value);
}

… then we get 0 and 6 when we log the entries.

If we loop through a map, we get the entries of the map like we do below:

const map = new Map([['a', 4], ['b', 5], ['c', 6]]);

for (const entry of map) {
  console.log(entry);
}

We log ['a', 4], ['b', 5], and ['c', 6].

Also, we can use the destructuring operator to break up the keys and values of each entry, like so:

for (const [key, value] of map) {
  console.log(value);
}

In the code above, we just log the values of map, which are 4, 5, and 6.

Sets are also iterable objects, so we can loop through them, like so:

const set = new Set([1, 1, 2, 2, 3, 6]);

for (const val of set) {
  console.log(val);
}

We should get 1, 2, 3, and 6 logged since sets eliminate duplicate values.

The arguments object is a special object that’s available in each function. It has the arguments passed into the object, regardless of what you defined in your parameters. We can loop through it with the for...of loop

For example, if we have …

(function() {
  for (const arg of arguments) {
    console.log(arg);
  }
})(4, 5, 6);

… then we log 4, 5, and 6 since that’s what we passed into the anonymous function as arguments.

While loop

The while loop will loop whenever a condition stays true.

For example, the loop below will run if the index number i is less than 3:

const array = [1,2,3];let i = 0;
while(i < array.length){
  console.log(i);
}

If the condition in the parentheses is never true, then the loop content will never run, and if it’s always true, then it runs forever, creating an infinite loop.

Do…while loop

The do...while loop will always execute the first iteration.

const array = [1,2,3];let i = 0;
do{
  console.log(i);
}
while(i < array.length)

In the example above, it will at least log 0, but it will also log 1 and 2 in this case since those two numbers are less than 3.

With the above loops, you can call break to stop the loop or return before the loop is completely finished.

//do while loop
const array = [1,2,3];let i = 0;do{
  console.log(i);  if (i == 1}{    break;  }}
while(i < array.length)//while loop
i = 0;while(i < array.length){  if (i == 1{    break;  }
  console.log(i);
}//for loop
for (let j = 0; j < array.length; j++){  if (j == 1){
    break;
  }
  console.log(j);
}

In the above examples, you will not see 2 logged.

An example of returning from within the loop:

const loop = ()=>{
  const array = [1,2,3];
  for (let j = 0; j < array.length; j++){
    if (j == 1){
      return j;
    }
    console.log(j);
  }
}
loop() //returns 1

You can also skip iterations with the continue statement:

const array = [1,2,3];
for (let j = 0; j < array.length; j++){  if (j == 1){
    continue;
  }
  console.log(j) // 1 will be skipped;
}

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.