# Understanding While Loop

Posted on

I am trying to understand what exactly happens when I use the ‘while loop’ to execute a code multiple times.

I was solving a problem on JSHero.net and I found it confusing so I tried explaining the solution to myself in order to get a clear understanding.

Please study the question, the answer and the simple explanation and let me know if I have understood it correctly.

Stay Safe !!

Question:

Write a function spaces that takes a natural number n and returns a string of n spaces.
Example: spaces(1) should return ‘ ‘.

function spaces (num) {

let mySpaces = ”;

while (num– > 0)

``````mySpaces += ' ';
``````

return mySpaces;

};

Explanation:

declare a function spaces
it has 1 parameter ‘num’
declare a variable mySpaces
initialize it with an empty string
we use a while loop as we need to repeat an action multiple times
in this case we need to add blank spaces to a string
our ”’empty spaces string”’ will be stored in the variable mySpaces
blank spaces will be equal to the ‘num’ parameter, which is fed when the function ‘spaces’ is called
while loops have: a condition and a code (loop body)
our condition is to ensure that the code should execute as long as the num is greater than 0
our condition is (num– > 0)
our code is: mySpaces += ”
so if our function is called with the following parameter then how would this while loop work

spaces (3)
first it will check if 3 > 0; which it is and it will execute the code
mySpaces = mySpaces + ‘ ‘; the result in variable mySpace will now be ‘ ‘ (1 space)
then since we have used the num as a counter (num–), the loop will reduce 1 from 3 = 2
it will check if 2 > 0; which it is and it will execute the code
mySpaces = mySpaces + ‘ ‘; the result in variable mySpace will now be ‘ ‘ (2 spaces)
then since we have used the num as a counter (num–), the loop will reduce 1 from 2 = 1
it will check if 1 > 0; which it is and it will execute the code
mySpaces = mySpaces + ‘ ‘; the result in variable mySpace will now be ‘ ‘ (3 spaces)
then since we have used the num as a counter (num–), the loop will reduce 1 from 1 = 0
it will check if 0 > 0; which it is not and it will only execute the code after the while loop
we return the mySpaces variable which will give us the final result