Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    6Topics
    |
    6 Quizzes
Lesson 7, Topic 4
In Progress

JavaScript: Looping through Arrays

Yasin Cakal 20 Nov 2021
Lesson Progress
0% Complete

for loops come in handy when it comes to iterating over data structures. A for loop, for instance, can be used to perform the same operation on each element of an array. Lists of data, such as customer names or product information, are stored in arrays. Assume we were the owner of a pharmacy and wanted to raise the price of every item in our inventory. That could be a lot of repetitive code, but we can easily accomplish this task by using a for loop to iterate through the array.

A for loop should use the array’s .length property in its condition to loop through each element in an array.

See how for loops iterate on arrays in the example below:

const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday', 'Saturday'];
for (let i = 0; i < days.length; i++){
  console.log(days[i]);
}

The following is the output of this example:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Our iterator variable is called i in the loop above. You’ll see this variable naming convention in a lot of loops. We can think of i as a shorthand for the word index when we use it to iterate through arrays. Take note of how our stopping condition verifies that i is smaller than days.length. Keep in mind that arrays are zero-indexed, so the index of the array’s last element is equal to the length of the array minus one. We’d gone too far if we tried to access an element at the index of days.length!

We can work with elements in arrays more easily with for loops.

Responses

Leave a Reply

%d bloggers like this: