Looping: Ruby vs. JavaScript
March 27th 2016
Keep on running…
Iterations are an essential component of computer applications. With some abstractio, we can model numerous real-life situations to iterations. A rather obvious example is a runner competing for the Olympic 10K medal. To run 10K, the runner will need to run 25 laps of 400m each.

In the examples below, you will find that both languages are capable of coming to the same result, only with a different syntax:
- Ruby:
-
25.times do |i|
puts (i + 1)*400
end - Ruby is a langage that is driven by readability for the programmer. The language has numerous built-in methods that are easy to understand, write or read, but that will in the background do the work.
- JavaScript:
-
for (var i = 1; i < 25; i++) {
console.log(i*400);
} - JavaScript on the other hand is focused on computer performance rather than readability. As a result, this language has much less built-in methods and required developers to design the logic from scratch in a very explicit way.
So how does it work?
Basically both iterations have the same end result, but follow a different path to get there. They both have however three essential components in their syntax:
- State: The current state of the variable.
- Condition: A condition, related to the iteration. A new iteration will be started IF the statement evaluates to true.
- Be careful not to create an infinite loop (a statement that will always evaluate to true)
- Iterator: Defines how to change the variable with each iteration. This is often used to break the looping and avoid an infinite loop.
A quick overview:
Ruby | JavaScript | Comment | |
---|---|---|---|
State | i = 0 |
var i = 1 |
Ruby's variable value starts at zero (0) by defaut wheras in JavaScript, these variables are often initiated with 1 |
Condition | i 25 |
i < 25 |
In Ruby, you will iterate '25' times. In JavaScript, you will have to explicitly say that i cannot go above the number of iterations |
Iterator | .times |
i++ |
In Ruby, you will iterate a number of 'times'. Behind the scenes, Ruby will translate this easy keyword to computer language. In JavaScript, you keep explicitly track of how you want to iterate. This allows more freedom to define the iteration (ie. if you want to skip some rounds etc.) |