Matei Andreea
Matei Andreea

Reputation: 11

Explain the Javascript code, pad to left or rightside of string

I am learning Javascript and trying to do some challenges on codewar. I have the code for a challenge and I am trying to understand the logic.

The code snippet of interest is the function padIt, which accepts 2 parameters:

  1. str - a string we need to pad with "*" at the left or rightside
  2. n - a number representing how many times we will pad the string.

My question is, why do they use n-- and not n++?

function padIt(str, n) {
    while(n>0) {
        if(n%2 === 0) {
            str = str + "*";
        }
        else{
            str = "*" + str;
        }
        n --;
    }
}

Upvotes: 1

Views: 330

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36594

Why n-- and not n++?

First of all notice the condition of while loop n>0. It means keep executing the while block. Means keep padding the string until n is greater than 0. Initially n is always greater than 1. So we need to decrease is in order to end the while loop.

If we use n++ instead of n-- the code will create infinite loop

Upvotes: 0

iFun
iFun

Reputation: 31

if you use n++ the while loop will never end since it is checking if n is larger than 0

imagine n is 3: n will be 4,5,6,7,8 then it is a infinite while loop

instead n represent how many times to pad the string so if you want to add 3 * n will go down from 3 to 2 to 1 and the while loop will end

Upvotes: 1

Related Questions