A JavaScript For Loop and While Loop Tutorial

2020-10-16 17:06:52 | #programming #javascript | Part 5 of 5

Tested On

  • Linux Ubuntu 20.04
  • Windows 10
  • macOS Catalina

Now that we know how to organize data sets in-memory, it's a good time to learn how to iterate over this data. Iteration is the process of repeating a set of instructions until a specified condition is met. So say you wanted to fetch the first 50 books from a database and store them into a JavaScript array for processing. You could create a loop that iterates over every single book in the array, and prints only the ones that were written by a certain author. Or published in a certain year.

JavaScript loops are named in relation to their syntax/structure. For example, a for loop uses the for keyword when declaring its parameters and conditions. A for...in loop can be written like so: for (var key in object). And a do...while loop uses the do { //something } while (condition) syntax. We'll provide full examples, below, including other variations of loops, but that's where their names are derived. We'll also explain use cases where one loop is most optimal, so you can understand why so many exist.

How to Create a JavaScript For Loop

A for loop requires a starting position, an ending position, and an incrementation rate that determines the pace or stride. We separate each parameter with a semicolon ;.

for (var i = 0; i < 9; i++) {
  console.log(i);
}
for Declares the for loop
var i = 0 Declares a new variable i, and sets it to 0. This i variable keeps track of the starting position, so any number would suffice. The variable name i is irrelevant, but i is the most common with for loops.
i < 9 This is the condition; keep iterating as long as i is less than 9. Feel free to set any ending position you'd like to expand to decrease the range to iterate over.
i++ Increment i by 1 on every iteration. i++ is a shorthand way of writing i += 1 or i = i + 1. If you only wanted to process every other element of the array, you would use i += 2. If you wanted to iterate in reverse, you would set the starting position to the max value, the ending position to the minimum value, and decrease on every loop with i--.

Now, let's learn the for loop's most common implementation—iterating over an array.

var numbers = [4, 5, 2, 3, 9, 6, 7];

for (var i = 0, len = numbers.length; i < len; i++) {
  console.log(numbers[i]);
}

for Declares the for loop
var i = 0 Declares a new variable i, and sets it to 0. If you want to use an existing variable, the var portion isn't necessary. This i variable keeps track of the starting position, so if you wanted to start at the 3rd element of the array, you would set i to 2. You can use any variable name, such as j or x, but i is the most common.
len = numbers.length Here, we assign the length of numbers to a fixed len variable. This means we don't have to keep reference the more expensive numbers.length. We now have 2 variables declared on one line (i and len), separated by a comma. The multiline equivalent of this is:
var i = 0;
var len = numbers.length;
i < len This is the condition; keep iterating as long as i is less than len. There's no need to keep going past the length of the array. If we only wanted to iterate over half of the array, in the previous section, we could set len to numbers.length / 2
i++ Increment i by 1 on every iteration. i++ is a shorthand way of writing i += 1 or i = i + 1. If you only wanted to process every other element of the array, you would use i += 2. If you wanted to go through the array in reverse, you would initially set i to numbers.length and use i--.

Everything inside the curly braces is the code to be executed on every iteration. In this case, we are just printing each element to the console. If we wanted to increment each element of the array by 1, we could put numbers[i]++; within the curly braces.

We can also put any manner of conditionals in the array, including ones that allow us to break out of the loop with the break keyword. The following examples shows us how to end the loop if either a 6 is found or the end of the array is reached.

var numbers = [4, 5, 2, 3, 9, 6, 7];

for (var i = 0, len = numbers.length; i < len; i++) {
  if (numbers[i] === 6) {
    break;
  }
}

How to Create a For...Of Loop

Similar to a regular for loop, but better suited for when you want to iterate over an iterable, such as an array. Notice how it's much more concise than the previous for loop.

var numbers = [4, 5, 2, 3, 9, 6, 7];

for (var x of numbers) {
  print(x);
}

How to Create a JavaScript For...In Loop

A for...in loop is better suited for when you want to iterate through the properties of an object. Let's review the following example:

var book = {
  title: 'Nineteen Eighty-Four',
  author: 'George Orwell',
  country: 'United Kingdom',
  published: '1949-06-08 00:00:00',
  pages: 328
}

for (var key in book) {
  print(key, book[key])
}

Again, we have to use the for keyword to declare our loop. We then declare the variable key to store the object key on each iteration, the in keyword, and book to indicate the object we want to iterate through. Within the curly braces, we can then access the objects keys and values, and do what we'd like with them.

How to Create a JavaScript While Loop

A while loop first declares the condition to be met, then declares the code to be executed.

var numbers = [4, 5, 2, 3, 9, 6, 7];
var i = 0;

while (i < len) {
  console.log(numbers[i]);
  i++;
}

While loops are less verbose than for loops, and are ideal for when you just want to execute some code on repeat, without needing to define a bunch of iteration parameters or an array, for that matter. Take the following example:

var flag = true;

while (flag) {
  // Execute some code
}

// ...Some other code
// ...Some more code
flag = false;

Above, we execute the code within the curly braces until another part of our program sets flag to false.

How to Create a Do While Loop

A do while loop executes the code prior to checking if the condition for ending the loop has been met. This guarantees that the code always executes at least once.

do {
  // Execute some code
} while (condition);

So if you wanted to execute a block of code 5 times, you could do the following:

var i = 0;

do {
  console.log(i);
  i++;
} while (i < 5);

A Real-World Loop Example

Let's piggyback off of what we learned in the previous chapter to iterate over an array of books, and display the ones that were written by a particular author.

var library = [{
    title: 'Nineteen Eighty-Four',
    author: 'George Orwell',
    country: 'United Kingdom',
    pages: 328,
    genres: ['dystopian', 'political fiction'],
    publisher: {
        'name': 'Secker & Warburg',
        'date': '1949-06-08 00:00:00'
    }
}, {
    title: 'Neuromancer',
    author: 'William Gibson',
    country: 'United States',
    pages: 210,
    genres: ['science fiction', 'philosophical fiction'],
    publisher: {
        'name': 'Ace',
        'date': '1984-07-01 00:00:00'}
}, {
    title: 'Do Androids Dream of Electric Sheep?',
    author: 'Phillip K. Dick',
    country: 'United States',
    pages: 210,
    genres: ['science fiction', 'philosophical fiction'],
    publisher: {
        'name': 'Doubleday',
        'date': '1968-00-00 00:00:00'}
}, {
    title: 'Snow Crash',
    author: 'William Gibson',
    country: 'United States',
    pages: 271,
    genres: ['science fiction'],
    publisher: {
        'name': 'Ace',
        'date': '1984-07-01 00:00:00'}
}];

// Using a for loop
for (var i = 0, len = library.length; i < len; i++) {
  var book = library[i];
  if (book.author === 'William Gibson') {
    console.log(book.title);
  }
}
  
// Using a for...of loop
for (var book of library) {
  if (book.author === 'William Gibson') {
    console.log(book.title);
  }
}
  
// Using a nested loop
for (var book of library) {
  for (var key in book) {
    console.log(key, book[key])
  }
}

Conclusion

That's the end of this tutorial. We hope you found it helpful. Make sure to check out our other tutorials, as well.

If you're interested in making interactives and games, we recommend you take our Learn JavaScript While Building a Game Framework course, which teaches you JavaScript and ES6 while you build an HTML5 Canvas, physics-based framework, from scratch. You'll also learn drag and drop, mouse following, velocity, acceleration, friction, and many other useful functionality you can build interactives and games with. In addition, it compiles into a browser-compatible ES2015 build. Start making canvas applications, today.

Want To See More Exercises?

View Exercises View Courses

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.



Tell Us About Your Project









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Hire Us

We offer web development, enterprise software development, QA &amp; testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

Contact