In this article, we have another fun algorithm challenge: steps
. It can be a little tricky if you haven’t seen it before, especially since the spaces must be logged to the console. Please try to solve this problem on your own before scrolling down to the solution.
Directions
- Write a function that accepts a positive number,
num
. - The function should print a step with
num
levels using the#
character. - Steps should have spaces on the right-hand side.
Examples
steps(2);
Output:
'# '
'##'
steps(3);
Output:
'# '
'## '
'###'
Let’s think about how we’re going to do this. See the image below to get a better idea.
{{< image title=“” w=“” h=“” o=“webp q100” p=“center” c=“rounded” src=“images/steps.png” alt=“Steps algorithm with JavaScript” >}}
As per the image above, the first step we’re going to do is write a for
loop. We’ll also want to declare a variable to store the spaces and the steps. The first for
loop we write is going to iterate through the rows, and the second for loop shall iterate through the columns, deciding if
the current column is equal to or less than the current row. If
it is, then add a '#'
. Else
, if it’s not, add a space to the variable declaration. As per the last step, we want to actually console.log()
the results (which will be stored in the variable).
Reminder: Before viewing the solution below, try to solve the problem yourself.
Solution
Below is a simple iterative solution, which makes use of two for
loops. Can you solve this problem in a different way? Post your solution in the comments below!
function steps(num) {
for (let row = 0; row < num; row++) {
let stair = "";
for (let column = 0; column < num; column++) {
if (column <= row) {
stair += "#";
} else {
stair += " ";
}
}
console.log(stair);
}
}
steps(4);
// Output:
// '# '
// '### '
// '#### '
// '#####'
Don’t forget to check out Cracking the Coding Interview, where you will learn how to solve algorithmic questions just like this, and lots more!
Topics
About the Author

Matt Fay
Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.
Discussion (Loading...)
Join the Discussion
Sign in to share your thoughts and engage with the JavaScript Today community.