I was trying to write a simple function that prints a multiplication table and came up with the solution below:
const oneToTwelveMultiplicationTable = () => {
[...Array(12).keys()].forEach((num1, i) => {
[...Array(12).keys()].forEach((num2, j) => {
console.log((num1 + 1) * (num2 + 1))
})
})
}
oneToTwelveMultiplicationTable()
It works fine and that's not the issue, the issue is, as I was trying to clean up the formatting of the response (I wanted a more table-like format), I made this edit:
const oneToTwelveMultiplicationTable = () => {
let result = []
[...Array(12).keys()].forEach((num1, i) => {
[...Array(12).keys()].forEach((num2, j) => {
console.log((num1 + 1) * (num2 + 1))
})
})
}
oneToTwelveMultiplicationTable()
That gives an error on the 4th line, which I was able to fix by adding a return in front of it:
const oneToTwelveMultiplicationTable = () => {
let result = []
return [...Array(12).keys()].forEach((num1, i) => {
[...Array(12).keys()].forEach((num2, j) => {
console.log((num1 + 1) * (num2 + 1))
})
})
}
oneToTwelveMultiplicationTable()
My question is why do I need that return? I am not trying to get the function to return a value, why does adding a return in front of the forEach fix the error, and why does adding a variable declaration cause an error in the first place? This should be uncomplicated but I'm not clear as to why this is happening.