Javascript Looping

Tags: javascript

A cookbook of Javascript looping techniques and to a lesser degree, object introspection.

Looping for values

Use the for...of combination:

> let arr = [5, 10, 15, 20]
> for (let i of arr){console.log(i)}
5
10
15
20
1
2
3
4
5
6

for...of returns the value of the loop iteration. It's the right tool.

Looping for index

If you need to track the index of a loop, do this:

> let arr = [5, 10, 15, 20]
> const arrayLength = arr.length
> for (let i=0; i < arr; i++){console.log(i)}
0
1
2
3
1
2
3
4
5
6
7

This technique is reliable and acts in a predictable fashion.

What's the difference between for...of and for...in?

Let's use both techniques on the same array and see what we get. First, the for...of combination:

> let arr = [5, 10, 15, 20]
> for (let i of arr){console.log(i)}
5
10
15
20
1
2
3
4
5
6

The for...of combination returns the value of the loop iteration. It's the right tool for this job.

Now, the for...in combination, which isn't recommended:

> let arr = [5, 10, 15, 20]
> for (let i in arr){console.log(i)}
0
1
2
3
1
2
3
4
5
6

for...in returns the index of the loop iteration.

Don't use for...in for looping!

Read problems using for...in with arrays!

Problems using for...in with arrays

for...in can fool you into thinking it's the right tool for iterating over arrays. This appears to work:

> let arr = [5, 10, 15, 20]
> for (let i in arr){console.log(i)}
0
1
2
3
1
2
3
4
5
6

But let's change things up a bit with some prototype manipulation:

> Array.prototype.icecream = function(){console.log("Ice cream!")}
> let arr = [5, 10, 15, 20]
> arr
(4) [5, 10, 15, 20]
1
2
3
4

The array has been proven to have four elements. Now let's iterate over the array using for...in:

> for (let i in array){console.log(i)}
0
1
2
3
icecream
1
2
3
4
5
6

Whoa!

What's going on is that the for...in is enumerating over the properties of array, not the values. Even if you avoid using prototypes, the same cannot be said for any library installed from NPM. Finally, there is no guarantee that values will be returned for...in in numeric order.

Avoid using for...in for iterating over arrays.

Reference: stackoverflow.com/a/3010848


Copyright © 2018 Daniel and Audrey Roy Greenfeld.
Site Map

Last Updated: 8/27/2018, 6:03:47 AM