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:

  • Defined array
  • Used for loop
  • Used a print statement
  • What differences did you find? Here's my list:

  • In JavaScript, when you are printing the result, you need to refer to the variable in the for loop.
  • In Ruby, there's more than one way to accomplish the code (of course!)
  • In JavaScript, you must set a variable starting point, indicate that the variable is less than the value, then tell it how much to increment by.
  • In JavaScript, you need to make sure you open and close your curly braces and use semicolons to end statements.
  • Hope this was helpful. If I missed anything hit me up on the social media. Check my links below!