Ruby & Js | while

Syeda Ismat Farjana
3 min readMar 2, 2021

While loop is a control flow statement that executes a block of code while the given condition states true. The moment the condition of running the block turns false the loop stops executing the code. it is normally used when the number of iteration of a program is not fixed. The evaluation of the state is done before the block execution.

Ruby syntax

while condition is truestatementend

As example:

x = 5while x >= 0
puts "I am on line #{x}"
x -=1
end

The given condition here is the while loop will execute the statement inside, till the value of x stays more than or equal to 0.

Each time the loop is running the statement is decrementing the given value of x by 1. The string interpolation is showing the decremented integer value.

JS syntax

while (condition is true)
statement

The while loop in js syntax is quite similar to ruby. Except for the condition is in parenthesis and the statement is in curly braces. While loop will execute the statement till the condition stays true.

let a = 0;
let b = 10;
while (a < 5) {console.log(`The value of a and b is: ${a} and ${b} `);
a++;
b += a;
}

The value of a is set 0 at the beginning. The condition is to run the statement inside the loop(logging a string with the values of a and b) till the value of a is less than 5.

The infinite while loop

# x = 0# while x < 5#   puts "I am on line #{x}"
# x -=1
# end

While loop will keep running till the value of x is less than 5( in this case). the problem is, The set value of x at the beginning is 0 which is already less than 5. So the code inside the while loop will keep running forever. Unless someone stops it.

The do … while loop

The do …while loop executes the statement until the given condition evaluates to false. The while condition is evaluated after the statement.

JS syntax

do
statement
while (condition);

Ruby syntax

loop do
statement
break if (condition)
end

For more reading:

Ruby while loop, do… while loop,

JS while loop,

Js do… while loop

--

--

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.