I am learning Javascript from the book Eloquent Javascript by Marijn Haverbeke, there is exercise at the end of second chapter(Program Structure). Write a loop that makes seven calls to console.log to output the following triangle:
#
##
###
####
#####
######
#######
I tried to solve it like using a for loop.
var hash = "#";
for(counter = 0; counter < 8; counter ++)
{
hash = hash + "#";
console.log(hash);
}
The problem is it's showing not showing the first line of the required output, how do I get that?
I would greatly appreciate any solution especially if it comes with a little explanation.
Similar to a While loop, a For loop consists of three parts: the keyword For that starts the loop, the condition being tested, and the EndFor keyword that terminates the loop.
So first the condition is checked, then the loop body is executed, then the increment.
Nice job since you're just starting.
You almost got it. Just declare the variable as an empty string.
// this is the line that needs to be changed
var hash = '';
for(....) {
hash += "#";
console.log(hash);
}
This way as you add to the "hash" variable inside the loop, it doesn't have that extra "#" from variable declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With