Javascript Each Loop: Myth or Reality?

After having one language under your belt, the next language should take significantly less time to learn as you already have learned how to learn a coding language. I definitely buy into this this idea. Learning Javascript after having learned Ruby was great and I was able to pick up on the overall gist a lot quicker, with the exception of Javascript’s loops. Or should I say loop. Because for the most part, Javascript likes using only one.type.of.loop.

This really threw me for…(wait for it) a loop

Maybe this is pretty common in other coding languages, but my little Ruby-oriented brain could not accept it. But alas, I had to accept it because Javascript is not going to change because I was peeved I couldn’t simply write an each loop, so this is me trying to embrace the JS for loop and its many possibilities.

Caution: not as salty about JS as she appears

The deets: Javascript only uses one type of loop, but it can be used to have the same functionality of all of Ruby’s different loops!

On this post, I am going to focus on Javascript’s version of a Ruby each loop

In Ruby, an each loop that will print each element in an array is written as follows:

numbers = [1,2,3,4,5]
numbers.each do |num|
puts num
end

A javascript loop requires a few more components to get the same output of each number printed individually. Let’s break it down

var numbers = [1,2,3,4,5]
for (var i = 0;)

We initially set an arbitrary variable called i equal to 0. We are going to use i to track the index of the elements in our numbers array. Next we want to dictate how many times we will iterate through the array. The second section of the each loop sets the number of times the loop will run.

var numbers = [1,2,3,4,5]
for (var i = 0; i < numbers.length;)

The last component tells the code what to do after each time the code runs. For an each loop, we want to increment i by 1 to iterate through the entire array.

var numbers = [1,2,3,4,5]
for (var i = 0; i < numbers.length; i++)

Once we have that, we can print the code! I typically like to create a block variable of sorts because I think it makes the code more readable, but that’s just my personal preference.

var numbers = [1,2,3,4,5]
for (var i = 0; i < numbers.length; i++) {
num = numbers[i];
console.log(num);
)

The tricky part of learning that second (or third, or fourth) language is trying not to simply take the same elements from your first language and change the syntax to the new one. You want to utilize this new language and all of its functionality rather than just taking your Ruby code and translating it into Python. When you expect the two languages to have the same functionality, you limit your use of both languages.

Good luck, friends!