Ruby & JS | for loop

Syeda Ismat Farjana
3 min readFeb 27, 2021

for(ruby) || for…of , for…in(js)

We will use one simple array of rainbow colors to see the use of for (ruby), for…of, for…in(js)

Ruby

For loop iterates over an array. While iterating, it executes a specific block of code once for each one of the expressions of the array.

rainbow = [ 'violate', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']for color in rainbow dop "One color of the rainbow is: #{color}"end// --- after running ruby <file name> in the terminal, we will see this ---// "One color of the rainbow is: violate"
// "One color of the rainbow is: indigo"
// "One color of the rainbow is: blue"
// "One color of the rainbow is: green"
// "One color of the rainbow is: yellow"
// "One color of the rainbow is: orange"
// "One color of the rainbow is: red"

JS

We need to use for…of to have the same result.

const rainbow = [ "violate", "indigo", "blue", "green", "yellow", "orange", "red" ];for (const color of rainbow) {console.log(`One color of the rainbow is: ${color}`);}// --- after running node <file name> in the terminal, we will see this ---// One color of the rainbow is: violate
// One color of the rainbow is: indigo
// One color of the rainbow is: blue
// One color of the rainbow is: green
// One color of the rainbow is: yellow
// One color of the rainbow is: orange
// One color of the rainbow is: red

If we use for…in to iterate over the array, we will get something different

const rainbow = [ "violate", "indigo", "blue", "green", "yellow", "orange", "red" ];for (const color in rainbow) {console.log(color);}// --- after running node <file name> in the terminal, we will see this ---// 0
// 1
// 2
// 3
// 4
// 5
// 6

For…in loop returns the index of each color, not the color itself.

The reason is:

In the case of Array iteration, for…in only logs the enumerable properties of an iterable object, in arbitrary order. In this case, the enumerable property is the index of each color name and the color names are the values.

for…in is used for debugging purposes, to see the properties of an object.

For instance, to understand for…in, we have an Object named rainbow that holds few key-value pairs.

const rainbow = {number: 7,color: ["violate", "indigo", "blue", "green", "yellow", "orange", "red"],occurance: "after rain",position: "opposite the sun"};for (const property in rainbow) {console.log(`${property}: ${rainbow[property]}`);}// --- after running node <file name> in the terminal, we will see this ---// number: 7
// color: violate,indigo,blue,green,yellow,orange,red
// occurance: after rain
// position: opposite the sun

for…in loop iterates over the objects enumerable and logs the property itself(key-value) as a string.

For more reading

js: for…of,

js: for…in,

ruby: for

--

--

Syeda Ismat Farjana

I am a physician, eager to learn Coding and eventually jump into the world of AI so I can work for the future.