Home > Blockchain >  Eloquent JavaScript looping a triangle exercise solution question
Eloquent JavaScript looping a triangle exercise solution question

Time:11-18

I had to check the solution for the first exercise in the book, and as I understand it, it's almost identical to my answer.

The exercise:

Write a loop that makes seven calls to console.log to output the following triangle:

the solution, that is given by the book:

    for (let line = "#"; line.length < 8; line  = "#")
    console.log(line);

and my solution:

    for (let hash = '#'; hash.length <= 7; hash  ) { 
    console.log(hash);
    };

My question is, why my loop doesn't loop? As it is explained in the book:

For counter = 1 and counter -= 1, there are even shorter equivalents: counter and counter--.

So by this logic, it should work.

CodePudding user response:

You are trying to increment a character. This doesn't concatenate to the character as you want it to and instead increases the ASCII value of the character.

Modify your code a bit:

for (let hash = "#"; hash.length <= 7; hash  = "#") {
    console.log(hash);
};

hash should be a string so that you can concatenate to it; furthermore, you shouldn't try to increment hash but rather concatenate to it on every iteration of the loop.

  • Related