Print a staircase pattern with nested loops

“Star staircase”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 5: Loops: Doing Things Over and Over teaches, and one test checks your answer.

The challenge

Write staircase(n) that prints n lines. Line 1 has one #, line 2 has two, and so on. Then call staircase(4).

Example
#
##
###
####

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • It prints:
    #
    ##
    ###
    ####

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

An outer loop for each line, and an inner loop (or "#".repeat(i)) to build that line.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function staircase(n) {
  for (let i = 1; i <= n; i++) {
    let line = "";
    for (let j = 0; j < i; j++) {
      line += "#";
    }
    console.log(line);
  }
}

staircase(4);

Learn what you need

This exercise uses what Grade 5: Loops: Doing Things Over and Over teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning