JavaScript Tutorial Series - Loops




Loops are used to run a block of code multiple times. JavaScript supports while loops, do while loops and several types of for loops.


While loops run a block of code until a condition is no longer true. A while loop condition needs to be carefully written. If the condition never fails, the loop will never stop. It will become an infinite loop that will hang the program and make it unresponsive. The following is an example of an infinite loop, so don't do this:


let i = 0;
while (i < 5) {
  console.log('i: ' + i);
}
This is an infinite loop because the i variable never changes. This loop is fixed by incrementing i as follows:

let i = 0;
while (i < 5) {
  console.log('i: ' + i);
  i++;
}
JavaScript also supports do while loops. This type of loop always executes once. Any further executions are dependent on the while condition. Example:

do {
  let i = 0;

  console.log('i: ' + i);
  i++;
} while (i < 5);
For loops run a block of code a given number of times. A for loop sets a variable to a start number. It has a conditional that compares the variable against and ending number. When the variable no longer meets the condition, the loop ends. The loop also sets the variable increment. Example:

for (let i = 0, i < 5; i++) {
  console.log('i: ' + i);
}
The above example sets the variable i to 0. As long as it is less than 5, it's value will be output to the console. After each loop execution, i is incremented by 1. JavaScript also supports for...in loops which are useful for iterating over object properties. Example:

let temp = {
  a: 'first',
  b: 'second'
};

for (let key in temp) {
  console.log('key: ' + key);
  console.log('value: ' + temp[key]);
}
The last type of JavaScript for loop is the for...of loop. This is useful for looping over iterables, such as Arrays, Strings, Maps, NodeLists, Set, and arguments to retrieve values.

let aString = 'letters';

for (let val of aString) {
  console.log('val: ' + val);
}
If you know how many times you want to run the same block of code, use a for loop. If you don't know, use a while loop. Implementation:
Inside the javascript_tutorial.js file created in the JavaScript set up tutorial, add the following lines that are in bold:

// JavaScript Tutorial

/*
* This file will add JavaScript
* to a website.
*/

(function() {
  let doc = document;
  let defaultLocation = [-86.7816, 36.1627]; // longitude, latitude



    let locationStr = '';
    for (let i = 0, num = defaultLocation.length; i < num; i++) {
      locationStr += defaultLocation[i];
      if (i === 0) {
        locationStr += ', ';
      }
    }

    console.log('Setting weather for location: ' + locationStr);



})();  
This is just a simple for loop example that will display in the console the coordinates of the location the weather is being displayed for. The JavaScript tutorial series starts with this post. (paid links) More JavaScript




Comments