This week we are starting to dive into JavaScript so I wanted to try and highlight a difference between it and Ruby. One aspect of computers that makes them particularly powerful and useful is the ability to cycle through lots of information very quickly. We achieve this with something called looping. Most languages support looping in one form or another. Both JavaScript and Ruby have the ability to loop but they do so in different ways. They share a loop known as a 'for' loop but they use them in different ways.
Let us see how a JavaScript 'for' loop looks first then we will break it down.
for (i = 0; i <= 10; i++) {
console.log("Hello World!")
}
We start out by declaring it is a for
loop. Simple enough. What follows that may confuse you so let's take it step by step. i = 0
is declaring our counter variable. We want to start at 0 in this case. We can change that to any number we want to start at. Next is i <= 10
. This is how long we are doing it. In English, it would read 'while i is less than or equal to 10'. The last part is i++
. This tells us how to count. The ++
means add 1. So this part is telling the program to add one to i after each time through the loop. Everything between the {}
's will run each time the program loops. Pretty cool, right?
Next, let us see how Ruby does it.
for i in 1..10
puts "Hello World!"
end
Again, we start out by declaring this as a for
loop. Next is where it can get a little tricky. i in 1..10
in English would read 'each number in between 1 and 10'. The program will start at 1 and count all the way up to 10. Each time, it will run the code inside the loop. In this case, that would be puts "Hello World!"
. As you can see it is a very simple set up yet can be very useful.