Navigating the differences between JavaScript and Ruby

Ruby Loops vs. JavaScript Loops

May 25, 2015

Our cohort has spent the last four weeks learning Ruby and getting to know its powerful built-in methods. This week we switched to do an introduction to JavaScript, and it was an awakening.

Overall, my experience with JavaScript has been far clunkier than Ruby, and I found the syntax take more time to grasp. So today, I'm going to dig more into looping and show how it looks differet in Ruby vs. in JavaScript.

Here's a challenge: calculate 2 to the power of 10 (e.g., 2^10). Over the next few couple examples we'll walk through how to solve this challenge in both Ruby and JavaScript. For each language, we'll also look at solving it with a few different types of loops.

In Ruby, we can start by calculating it using a times do loop. We want to set the result at the beginning to 1. Effectively by the end we want to get 2x2x2x2x2x2x2x2x2x2. Here's the first way to set it up:

result = 1
10.times do
result = result * 2
end

puts result
# => 1024

Perhaps, instead we want to caculate this using a while loop. This time we want to set our result and our counter. This modifier will continue to execute the code while the conditional is true.

result = 1
counter = 0

while counter < 10 do
result = result * 2
counter +=1
end

puts result
# => 1024

Perhaps, instead of while we actually would like to use an until loop. This modifier will continue to execute the code while the conditional is false.

result = 1
counter = 0

until counter > 9 do
result = result * 2
counter +=1
end

puts result
# => 1024

Let's look at some of these examples in JavaScript. In the following example, we need to use a new set of syntax. In JS, you'll notice that the variable has to be explicitly called out. So "result = 1" will only work in Ruby. In JS, the parallel syntax must be "var result = 1". Additionally the while loop requires the conditional in parentheses, and then will perform the execution required in the curly brackets.

var result = 1;
var counter = 0;
while (counter < 10) {
result = result * 2;
counter +=1;
}
console.log(result);
// → 1024

Now let's try this using a for loop in JS. We still set the result in the beginning, but now we set the counter after the for construct. Of note, the parentheses after a for keyword must contain two semicolons. The first part initializes the loop by defining the variable. The second part checks whether the loop must continue (e.g., the conditional), and the final part updates the state of the loop after every interation.

var result = 1;
for (var counter = 0; counter < 10; counter += 1) result = result * 2;
console.log(result);
// → 1024

Of note, the for construct in JS generally is shorter and clearler than the while construct. But generally these looping functions in JS require more syntax than Ruby's powerful built-in methods.