grayscale photo of computer laptop near white notebook and ceramic mug on table
Javascript Programming

How to make a triangle using a loop in Javascript?

Problem comes from https://eloquentjavascript.net/02_program_structure.html:

Looping a triangle

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

#
##
###
####
#####
######
#######

It may be useful to know that you can find the length of a string by writing .length after it.

let abc = "abc";
console.log(abc.length);
// → 3

My solution using a while loop:

let hash = "#";

 while(hash.length <=7){
     console.log(hash);
     hash = hash + "#";
 }


My solution using a for loop:

for(let i=0; i<=6; i++){
    console.log(hash)
    hash = hash + "#"
}
    

Leave a Reply