JavaScript Basics | Loops cover image

JavaScript Basics | Loops

Jonathan Barrios • September 8, 2020

javascript

Introduction

Welcome to the JavaScript Basics series for beginners. In part 8 of JavaScript Basics, we'll dive into loops such as for, while, do-while, and looping through arrays. See you there!

Prerequisites

To get the most out of this course, you should know:

In Part 8 of JavaScript Basics, we'll focus on:

Future JavaScript Basics posts include:

Note: It takes years of focused practice to become a great JavaScript engineer. This JavaScript Basics course introduces JavaScript fundamentals and will improve your coding skills, but don't expect to transform into a JavaScript expert overnight instantly. Remember, the JavaScript learning journey is a marathon, not a sprint.

Loops

For, while, and do while loops are the most common loops found in most programming languages. Here are a few examples to try out:

for

The for statement is a loop of three (optional) expressions, wrapped in parentheses and separated by semicolons, then a statement gets executed in a loop.

// For loop
for (let i = 0; i < 10; i++) {
  console.log(i);
}
// Now print Two! when 2 is returned
for (let i = 0; i < 10; i++) {
  if (i === 2) {
    console.log('Two!');
    // continue
    // break
  }
  console.log(i);
}

while

The while loop executes a specified statement when the condition evaluates to true. The condition gets evaluated before executing the statement.

// While loop
let i = 0;

while (i < 10) {
  console.log('Number ' + i);
  i++;
}

do-while

The `do-while statement is a loop that executes a statement until a condition evaluates to false. The execute statement executes at least once.

// Do while
let i = 0;

do {
  console.log('Number ' + i);
  i++;
} while (i < 10);

Loop through arrays

We can also loop through arrays.

// Loop though arrays
const motorcycles = ['Honda', 'Suzuki', 'Harley'];
for (let i = 0; i < motorcycles.length; i++) {
  console.log(motorcycles[i]);
}

foreach

The forEach() method provides a function once for each array element.

// Foreach
motorcycles.forEach(function(motorcycle) {
  console.log(motorcycle);
});

map

The Map object contains key-value pairs and remembers the original insertion order of keys. Any value may be used as a key or value.

// Map
const users = [
  { id: 1, name: 'Jonathan' },
  { id: 2, name: 'Sarah' },
  { id: 3, name: 'Toby' },
];

const ids = users.map(function(user) {
  return user.id;
});
console.group(ids);

Now that you finished part 4 of JavaSctipt Basics, we'll begin learning about JavaScript Objects in Part 5. Follow me on Twitter @_jonathan_codes for more JavaScript Basics and other web development frameworks, databases, and more. As always, Happy coding! 👋🏼