Multiplication table using nested for loops
Here's one practical exercise showing when to use nested for loops in JS
By: Ajdin Imsirovic 03 December 2019
Has anyone ever asked you: “When would you use a nested for loop?”. Here’s a fun little exercise showing a practical application in making a multiplication table.
Image by CodingExercises
How to make a multiplication table in a nested for loop
Here’s the complete code:
let multiplicationTable = [];
for(let i=1 ; i<11 ; i++){
for(let j=1 ; j<11 ; j++){
multiplicationTable.push(`${i} times ${j} is ${i*j}`);
}
}
console.log(multiplicationTable);
Alternatively, we can replace the innermost array.push
with a simple console.log
call:
console.log(`${i} times ${j} is ${i*j}`);
Either way, a multiplication table will be printed to the console.
Bonus: Domain-name generator
Another simple exercise is to use nested for loops to build some custom domain names:
let prefix = ['big', 'important', 'very', 'cool', 'super' ];
let word = [ 'code', 'coders', 'tech', 'stack', 'geeks', 'computing' ];
for(let i=0; i < prefix.length; i++) {
for (let j=0; j < word.length; j++) {
console.log(`${i}${j}.com`);
}
}
The above naive approach will not result in the desired outcome. Instead, it will produce this:
00.com
01.com
02.com
...
45.com
What are we missing here?
We’re missing the fact that we’re working with arrays. So, working code will look like this:
let prefix = ['big', 'important', 'very', 'cool', 'super' ];
let word = [ 'code', 'coders', 'tech', 'stack', 'geeks', 'computing' ];
for(let i=0; i < prefix.length; i++) {
for (let j=0; j < word.length; j++) {
console.log(`${prefix[i]}${word[j]}.com`);
}
}
With the above fix, our code will concatenate each member of the prefix
array to each member of the word
array, and tack on .com
to the end.
This will result in a list of domain names being logged to the console.
We can even add all the domain names to our browser’s screen, like this:
document.body.innerHTML = "";
let prefix = ['big', 'important', 'very', 'cool', 'super' ];
let word = [ 'code', 'coders', 'tech', 'stack', 'geeks', 'computing' ];
for(let i=0; i < prefix.length; i++) {
for (let j=0; j < word.length; j++) {
let div = document.createElement('div');
div.innerText = `
${prefix[i]}${word[j]}.com
`
document.body.appendChild(div)
}
}
Now our domain names are being displayed on the screen, making it much easier to copy-paste.
This is the full list of generated domain names:
bigcode.com
bigcoders.com
bigtech.com
bigstack.com
biggeeks.com
bigcomputing.com
importantcode.com
importantcoders.com
importanttech.com
importantstack.com
importantgeeks.com
importantcomputing.com
verycode.com
verycoders.com
verytech.com
verystack.com
verygeeks.com
verycomputing.com
coolcode.com
coolcoders.com
cooltech.com
coolstack.com
coolgeeks.com
coolcomputing.com
supercode.com
supercoders.com
supertech.com
superstack.com
supergeeks.com
supercomputing.com
This completes our fun little exercise showing the usage of nested for loops.