For Loop - Ruby vs Javascript
Nichole Shelton
December 16, 2014
Learning Ruby was an uphill battle for me. When we started JavaScript, I realized how much I learned from Ruby and that gave me a pretty big boost in confidence. Some things are the same (which is so sweet!) and some things are different. For this blog post, we'll take a look at the for loop in both Ruby and Javascript.
First, let's review the term loop and iteration. Iteration is essentially going through a group of items (like an array) and doing something to each item in the group. For the examples below we'll iterate through an array of numbers using a for loop and tell the program "print each item in the array please!".
Ruby - For Loop
Dearest Ruby of COURSE has multiple ways to execute a for loop. Below, we'll take a look at 2 of the most common ways.
array = [1, 2, 3, 4]
for num in array
puts num #print each num on its own line
end
output:
1
2
3
4
=> [1, 2, 3, 4]
Easy right. Now let's look at how to do this with the .each method.
array = [1, 2, 3, 4]
array.each do |num|
puts num
end
output:
1
2
3
4
=> [1, 2, 3, 4]
Same output. Now let's look at JavaScript. Although there is a way to use the each method, I'm going to show the most common way to do this in JavaScript.
var array = [1,2,3,4];
for (var i = 0; i < value; i++) {
console.log(array[i]);
};
output:
1
2
3
4
undefined
What similarities did you notice? This is what I noticed:
What differences did you find? Here's my list:
Hope this was helpful. If I missed anything hit me up on the social media. Check my links below!

