First, let’s simplify the function so you understand better, without changing your behavior.
The native function console.log
displays a log message in the browser console and will never return any value. This implies that when you associate the returned value to a variable it will be undefined
. Behold:
const retorno = console.log("Mensagem de log");
console.log("Retorno", retorno);
So its function is actually:
function dotinha(nome) {
console.log(`'heroi é: ${nome}`);
return undefined;
}
That is, the return of its function at all times will be undefined
.
Now, analyzing the behavior of forEach
. If you read the documentation you will see that the first parameter that forEach
waiting is the callback
, which is described as "function to execute on each element, taking three arguments". That is, the function forEach
expects to receive a function as parameter.
When you do heros.forEach(dotinha)
you are passing a function, so it will work. However, when you do heros.forEach(dotinha())
you’re passing the function return as parameter, because the parentheses there will indicate that you want to call it. As your function always returns undefined
you’re actually passing by undefined
as a parameter of forEach
, therefore the error cited.
error: Undefined is not a Function
Even, realize that when you do this appears the message 'heroi é: undefined
before giving the error, because as you made the call without identifying the parameter, dotinha()
, the value of nome
in the role will also be undefined
.
const heros = ['visage', 'enchant', 'lone']
function dotinha(nome) {
return console.log(`'heroi é: ${nome}`)
}
heros.forEach(dotinha())
If the idea is just to display the message to each hero, you don’t need to return
function. Indeed, when used in conjunction with the forEach
it will never make sense to have the return
, for the forEach
ignores the return.
It is also possible to use anonymous functions:
const heros = ['visage', 'enchant', 'lone']
heros.forEach(function (nome) {
console.log(`Herói é: ${nome}`)
});
Or use the Arrow functions:
const heros = ['visage', 'enchant', 'lone']
heros.forEach(nome => {
console.log(`Herói é: ${nome}`)
});
Or use the for
javascript:
const heros = ['visage', 'enchant', 'lone']
for (let nome of heros) {
console.log(`Herói é: ${nome}`)
}
As homework:
Thanks for the reply Anderson, helped dms!!
– Reubber
@Reubber I added a few more details if you’re interested.
– Woss