Reversing a line of ”#” using a for loop?

hello,

I’m working on a simple program that logs a ”triangle” made up of hashes (#) to the console. Using the for loop:

for (let lineOne = “#”; lineOne.length <= 7; lineOne = lineOne + “#”)
console.log(lineOne);

which logs the following to the console:

#”
##”
###”
####”
#####”
######”
#######”

Next, I would like to reverse the loop, starting with a logging 6 hashes and then reducing one for each line until ending up with 1. Like so:

######”
#####”
####”
###”
##”
#”

I’ve attempted the following, which doesn’t work:

for (let lineTwo = “######”; lineTwo.length = 1; lineTwo = lineTwo - “#”)
console.log(lineTwo);

Any suggestions on how I could make this work and end up with the following pattern logged to the console:

#”
##”
###”
####”
#####”
######”
#######”
######”
#####”
####”
###”
##”
#”

Thanks and hope others can benifit from this too :slight_smile:

Hi there.

I’ve quickly used my browser’s JS console to illustrate why your approach doesn’t work:
image

In the context of strings, + becomes a concatenation operator and JavaScript understands that by using it you mean “combine these two strings”.

It does not understand the inverse - the - operator when used on a string does not change to a “separation” operator. JavaScript attempts to do subtraction, but can’t because subtracting a string from a string makes no sense, so you get the result of “Not a Number” (NaN).

Perhaps there is a string instance method which might allow you to achieve what you’re aiming to do? :slight_smile:

1 Like

Thanks for taking the time to explain this so well. It makes sense to me now.

:slight_smile:

1 Like