Register to get access to free programming courses with interactive exercises

for loop JS: Arrays

Working with arrays almost always tied to simultaneous processing all of its elements. This is needed when printing lists, performing various calculations, or checking data. In all these cases, you need a mechanism to iterate through the elements of the array. The easiest way to do this is to use a loop.

Traversing

Loops are not directly related to arrays, but loops have a counter that can act as an array index. Therefore, it's not difficult to use them together:

// Create an array
const userNames = ['john', 'nancy', 'eugen'];

// Define the loop
// The initial counter value is i = 0 – it's calculated once, before execution starts
// Stop condition is i < userNames.length – it's executed before each iteration
// i += 1 – is performed after each iteration to go to the next index
for (let i = 0; i < userNames.length; i += 1) {
  // This code is executed for each element
  console.log(userNames[i]);
}

// => 'john'
// => 'nancy'
// => 'eugen'

In this code, we create an array of three elements, which are names. Then we traverse the array and display all the names so that each name is on a new line (console.log automatically inserts a line break).

Let's consider this stage in more detail. When you traverse an array with a for loop, the counter usually plays the role of the array index. It's initialized with a value of zero and incremented up until userNames.length - 1, which corresponds to the index of the last element. This is why we use strict comparison < (less than) in the conditional expression i < userNames.length, not <= (less than or equal to).

But what if we need to output values in reverse order? There are two ways to do this. One is to go in direct order, i.e., from the zero index to the last, and each time calculate the desired index using this formula, array size - 1 - current counter value.

const userNames = ['john', 'nancy', 'eugen'];

for (let i = 0; i < userNames.length; i += 1) {
  const index = (userNames.length - 1) - i;
  console.log(userNames[index]);
}

The other way involves traversing in reverse order, from the upper bound to the lower bound, that is, from the last array index to the first (which is zero, since indexing starts with zero). In this situation, the code changes to the following:

const userNames = ['john', 'nancy', 'eugen'];

// The initial value of i corresponds to the last index in the array
for (let i = userNames.length - 1; i >= 0; i -= 1) {
  console.log(userNames[i]);
}

In this workaround, the stop condition must specifically use >=⁣; otherwise, the loop won't get to element 0.

Modifying

When traversing an array, it can not only be read, but also modified. Suppose that we have the task of normalizing a list of e-mail addresses, for example, by making them lowercase. Then the code will look like this:

const emails = ['JOHN@gmAil.com', 'NaNCy@yes.COM', 'netiD@yahOo.CoM'];

console.log(emails);
// => [ 'JOHN@gmAil.com', 'NaNCy@yes.COM', 'netiD@yahOo.CoM' ]

for (let i = 0; i < emails.length; i += 1) {
  const email = emails[i];

  // toLowerCase() is a standard js method,
  // converting string to lowercase
  const normalizedEmail = email.toLowerCase();
  // Replacing the value
  emails[i] = normalizedEmail;
}

console.log(emails);
// => [ 'john@gmail.com', 'nancy@yes.com', 'netid@yahoo.com' ]

Key line: emails[i] = normalizedEmail;. It overwrites the element under index i.

Summary

The for loop can be combined with arrays in any way. You don't have to go through the whole array from beginning to end. You can, for example, look at every other item or only look at half of it. It all depends on the specific task.

Similarly, arrays are combined using while. The only thing arrays need is an index.


Recommended materials

  1. Documentation

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY