Select Page

Print all the multiplication tables with numbers from 1 to 10 with a `for-loop`.

## Explanation

With this challenge, a function is the best choice to accomplish the task. If you aren’t familiar with functions. No reason to worry.

But first, if you accomplished this task with 10 different for loops. Your solution isn’t wrong. The code does what it should do and hopefully right then. To enter the next level: 10 `for-loops` aren’t a good thing. Below I got a link to a Medium article of mine to show you more coding techniques that aren’t good.

Coming back to our solution. Code repetition is not a good practice. Even though the code does things slightly different. A rule of thumb: If two parts of source code look the same in 50% of lines, merge them into one part.

Avoiding code repetition means having reusable tools. A function suits that perfectly. A function provides input parameters. These are the settings for the function to operate with. Inside the body of the function, you have the reusable code pieces that operate slightly differently, depending on what you’ve put into the function as a parameter.

Now really back to the solution: Having a for-loop to with a function call to printTable() inside will execute the function 10 times since we configured the head of the `for-loop` to do it 10 times. The function `printTable()` has an input parameter of `n`. The `for-loop` passes the variable `i` every iteration, respectively, the values of 1 to 10.

You can now assume what the function must do. Right, the body is almost identical to the previous challenge, where you just print out one multiplication table. We changed the hard-coded 6 to an `n` and linked this variable to the input parameter of the function, resulting in a function that prints out the multiplication table of the number we pass to it as a parameter.

Because the function does it for any number and once per call, we can just call it ten times with corresponding parameters and we got our solution right away!

The line of `console.log("");` just prints out an empty line as a divider for the multiplication tables.

Follow me on Instagram and don’t miss the latest Challenge!

https://www.instagram.com/arnold.code/

## Find out what many programmers do wrong and be better!

Here is a pre-picked and high quality Medium article for you!