JavaScript Basics | Loops cover image

JavaScript Basics | Loops

Jonathan Barrios • September 8, 2020



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!


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 is an introduction to 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.


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


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++) {
// Now print Two! when 2 is returned
for (let i = 0; i < 10; i++) {
  if (i === 2) {
    // continue
    // break


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)

do while

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

// Do while
let i = 0

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

Loop through arrays

We can also loop thourgh arrays.

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


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

// Foreach
motorcycles.forEach(function(motorcycle) {


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 = {

Now that you finished part 4 of JavaSctipt Basics, we'll begin learning all 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! 👋🏼