JavaScript For Loop Iteration Simplified

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript For Loop Iteration Simplified

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Basics

const people = [
{ name: 'jane' },
{ name: 'john' },
{ name: 'jack' },
];

for (let index = 0; index < people.length; index++) {
const person = people[index];
console.log('Person:', person.name);
}

Optional Sections

Optional Pre:

let index = 0;

for (; index < 5; index++) {
console.log(index);
}

Optional Post

let index = 0;

for (; index < 5; ) {
console.log(index);
index++;
}

Infinite Loop:

let index = 0;

for (; ;) {
console.log(index);
index++;
}

for of

const people = [
{ name: 'jane' },
{ name: 'john' },
{ name: 'jack' },
];

for (let index = 0; index < people.length; index++) {
const person = people[index];
console.log('Person:', person.name);
}

for (const person of people) {
console.log('Person:', person.name);
}

break

const places = ['paris', 'london', 'tokyo', 'sydney'];
const favourites = ['beijing', 'tokyo', 'istanbul'];

let match;
for (const place of places) {
for (const favourite of favourites) {
if (place === favourite) {
match = place;
break;
}
console.log([place, favourite]);
}
if (match) break;
}

console.log(match);

continue

/**
* print numbers 0-14
* … but
* skip any number divisible by 3
* skip any number divisible by 5
*/

for (let index = 0; index < 15; index++) {
if (index % 3 === 0) continue;
if (index % 5 === 0) continue;

console.log(index);
}

for in

const point = { x: 3, y: 1, z: 2 };

for (const key in point) {
const value = point[key];
console.log(`${key}: ${value}`);
}

Object.entries(point);
[
['x', 3],
['y', 1],
['z', 2],
];

for (const [key, value] of Object.entries(point)) {
console.log(`${key}: ${value}`);
}
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Just like other scenes by programming languages. JavaScript also supports the standard index-based fall loop format. Consider a simple array of people each with their own name, Jane, John, and Jack. We can actually loop through the items of the array quite easily by using the JavaScript for loop. The standard follow loop consists of the four keyword followed by an initialization statement, followed by a conditional termination expression and an afterthought statement. The follow loop comes with a body block and you can put as many statements as you want within that.

00:32

The objective of this simple follow loop is to log the names of all of the persons within the people array. Here's how the basic follow loop runs. It starts off by running the initialization statement. Next, it checks if the condition expression is true, and if it is, then it runs the body of the follow loop. Next, it runs the afterthought statement, and then we basically start to loop around checking the expression. If it's true, running the body, running the afterthought and this loop will continue as long as the condition expression continues to be true. In our simple example, we are starting off at index zero.

01:05

We look up the person from the array using the index and lock out the person name. Next, we increment the index by one, and if index is still within the bounds of the array, we repeat the process fill index is no longer less than the length of the array, at which point we terminate the loop. You might recall that JavaScript arrays are zero indexed, which is why we start the loop at zero and terminate it at length, minus one, also known as index less than length. A little known fact about the standard follow loop is that the initialization, the condition and afterthought sections are actually all optional. So instead of using the initialization section of the four loop,

01:41

we could initialize a variable externally and this would function exactly the same as if we had written a let index equal to zero. Within the four loop here we are starting at index zero and terminating before five. So we can see on the console we have a 0 1, 2, 3 4. Similarly, instead of using the afterthought section of the fall loop, we could do whatever modification we need to make within the fall loop and leave that section out from the fall loop. And this functions the same as if we had put that statement in the afterthought, and we can even take the condition expression and leave that out to truly prove that all of these sections are optional. Now in this particular case,

02:16

since there is no terminating condition, this particular program will execute indefinitely logging incrementing numbers to the console till of course we exit the program. Modern js script comes with a four off loop that allows you to conveniently loop through arrays and other intervals in a simpler fashion when compared to the traditional index-based fall loop. Here we have the same array of people, Jane, John, and Jack, and we are using an index-based fall loop to log the person names. We can actually achieve the same functionality with the more modern JavaScript. For of loop four off loop consists of the four keyword followed by a variable

02:52

declaration followed by the off keyword, followed by the item that we want to iterate. Over here we are iterating Over the people array and for each iteration of the loop, we are storing an individual item into the person variable. So the first time this loop runs person is going to be the object that contains the name property with Jane. The next time it's going to be the object with John, and finally it'll be the object with Jack. In each iteration of the loop, within the loop body, we are logging out the person's name. So functionally it is going to be the same as the index-based for loop that we wrote before, but as you can see, it is much neater.

03:25

Since we don't need anex readable, we don't need to do plus plus and we can use constantly declare the current item upfront. There is less likelihood of making silly mistakes. So unless you have an explicit use case for the index variable in modern JavaScript, four off is the way to go. All JavaScript for loops support early termination with the use of the break statement, consider a simple array consisting of a few places around the world. We also have a separate array consisting of a few favorites. Our mission is to find the first place that also exists within our favorites array. For this,

03:59

we loop through the places with a simple four of loop and then we loop through the favorites within that using another four of loop. If at any point the place that we are looking at is the same as the favorite that we are looking at, congratulations, we have found a match. Now that we have found our answer, it would be useless to continue to loop through the favorites. We can exit out of the fall loop by using the brake statement to demonstrate that the fall loop will exit. Let's put a simple log statement so that we can be sure that we are not looking at any more items. Now, once we have the match, there's no point in looping through the places either, so we will make sure that if we have a match,

04:33

we will break out of that fall loop as well. Finally, at the end of the two fall loops, we log out the match that we have found. If you look at the two arrays, the only thing that is common is Tokyo. So we should look at Paris, London, and Tokyo from places first being compared to Beijing and then being compared to Tokyo and the loops terminating. And when we run this code, that is exactly what happens thanks to the break statements, we terminate the loops as soon as the match is found. You can use the continuous statement to jump to the next iteration of the loop. Essentially skipping over rest of the loop body for the current iteration. Consider the simple task of printing out numbers zero to 14, but skip the log.

05:11

If the number is divisible by three or if it is divisible by five, we can iterate from zero to 14 with a simple index-based follow loop within the loop, we check if the index is divisible by three, and if it is, we skip the remaining body with the continued statement. We can do the same thing with the other requirement as well. So if the index is divisible by five, we skip over the body with a continued statement. Finally, for all of the other index values, we simply log them to the console. If you run this code, you can see that it matches our expectations. Anything that is divisible by three or five is not getting logged to the console. JavaScript also comes with a four in loop,

05:47

but it's more of a traditional feature that you really want to use in modern JavaScript as there are better ways to achieve the same effect. The foreign loop is designed to be used with objects. So here we have a simple object called Point that has properties X, Y, and Z with values three, one, and two. As you might recall from our lesson on objects, we can actually use the strings X, Y, and Z to look up the values of these properties from the point object. Using a string in such a fashion is called a key, and that is exactly what is returned in each iteration of the four in loop. So when we iterate over the point object using a four in, it'll be the string X,

06:25

then the string Y, and then the string Z. We can use this key to look up the value for the property from the point object. For X, it'll be three. For Y, it'll be one, and for Z it'll be two. Let's log out the key and the value for each iteration of the loop. And as you can see, it matches our expectations. We have the keys X, Y, and Z with values three, one, and two. Now as I mentioned, the four in loop is sort of frowned within modern drow script because it's really up to you to make sure that when you get the key, you get the value for that corresponding key. Fortunately, there is a function on the object module that does disassociation for you

06:59

upfront, decreasing the chances of mistakes. The object entries function takes an object and returns an array of couples with each item containing the key and the value already associated for you. So if you have this array, we can actually just use our standard four off loop to loop through these entries each time destructing the keys and the values into their appropriate variables. So if you log out the keys and the values, again, you can see that this four off is equivalent to the previous four in additionally, objector entries works more reliably compared to four in when it comes to modern

07:34

JavaScript features like symbols. Many times when you are working with arrays in JavaScript and you want to loop through the items, instead of using the for loop, you can actually just use the array built in methods. Consider this very simple array of car manufacturers. We can log out the cars with a very simple four off loop, and for each car we use console log. Now instead of the four off, we could just as easily do cars four each and pass that individual item into console log. The JavaScript four off loop and the four each array method both achieve the same thing and it's up to you to decide which one looks better for you.

08:09

I personally like the four each. In this particular example, there are other cases where the JavaScript array built in methods can drastically save you from writing a lot of code within a four of yourself. As an example, consider the bullion has already, which we want to be true. If the car's array contains Audi, we can determine this quite easily by looping through all of the cars, checking if the car is equal to Audi. And if it is, then has Audi is equal to true and we can break from this four loop, but there is a JavaScript array method that can achieve the same effect with lesser code. We use the find index method to see if any car is equal to odi,

08:44

and if the response from find index is not equal to minus one, that means that we have found a result and therefore has ODI needs to be true. So the guidance is if you need to do something complicated that depends upon multiple inputs, then use the four loop. Otherwise, if it is something that falls into a category of an array utility method, then just use the method. A key reason why you might prefer a four off loop over the array for each is that for each does not support early termination, but you can use another array reiteration method to achieve the same effect of continue and break in a more functional programming inspired pattern.

09:19

Consider a simple input array consisting of a few numbers. With the four loop we want to skip. If the value is two, terminate the four loop. If the value is five, otherwise log the value to the console. We can look through the input with a simple four off loop. If the value is equal to two, we continue to skip. If the value is five, we break the loop with break, otherwise we log the value to the console. So for this input array, the loop will print three, skip over two, print seven and four, and then terminate at five. And if you run this code, that is exactly what we see on the console. No surprises here.

09:53

Let's see how we can achieve the same effect with a simple array iteration method. For the array iteration methods. If you want to continue, you're pretty much going to simply return from the callback function, but the difficulties in the break statement. And for that, we need to utilize the fact that some of the early iteration methods will stop iterating as soon as they have the answer that they are looking for. The simplest example is the fine method, so we can actually look through the input with the fine method. If the value is equal to two and we want to just jump to the next item, we do a simple return. Otherwise, if you want to terminate, for example, on value is equal to five, we simply return true and this signals to find that,

10:30

hey, we have found a item which essentially terminates the loop for all other items, we simply follow our requirement and lock the value. As you can see, the output from four off matches the fine method. For both of these we see 3, 7, 4. Personally, I would just use the four off loop, but bending functions to your will is a pattern worth knowing if only to understand the existing code bases out there. I hope you enjoyed this tutorial. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36