Whenever in doubt, see documentation, typically the MDN.
The documentation specifies the method forEach
as follows:
Syntax:
arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
Note that the forEach
gets a callback, i.e., a function only. Looking at your code has exactly that:
Carros.forEach(imprimir)
^---- callback
Then this function passed will receive several values as arguments. Let’s look at the documentation again:
callback
Function to execute on each element, taking three arguments:
currentValue
The current value of the element being processed in the array.
index
Optional The index of the current element being processed in the array.
array
Optional The array foreach() is being applied.
So taking your job:
function imprimir(nome, indice){
You see that the parameter nome
corresponds to the currentValue
indicated in the documentation, and indice
at the index
. I remind that the parameters can have the name you want, because they are assigned by order and not by name.
If you needed you could also access the array itself, adding one more parameter for this:
function imprimir(nome, indice, array){
These values are passed to their function by the forEach
, without you having to do more for it. Just have to interpret them and execute the intended logic.
As a matter of curiosity, here is an example of the implementation of forEach
(put as meuForEach
, to make clear):
//exemplo de implementação do forEach.
//O Array.prototype é para que a função fique no objeto Array com o nome meuForEach
Array.prototype.meuForEach = function(callback) {
//dentro do array o this refere o proprio array
for (let i = 0; i < this.length; i++){
//chamando sua função(callback) com o elemento, a posição e o array
callback(this[i], i, this);
}
};
//o mesmo código que você ja tinha mas agora usando o meuForEach
const Carros = ['Mercedes', 'Ferrari', 'BMW']
function imprimir(nome, indice){
console.log(`${indice + 1}. ${nome}`)
}
Carros.meuForEach(imprimir) //meuForEach em vez de forEach
I see the opposite in relation to the use of
forEach
: if you do not have a strong reason for the performance or flexibility offor
imperative, I prefer the declarative version because it is more readable. Readability, where I have worked, is the first goal, as long as it does not negatively (sensitively) interfere in performance– Jefferson Quesado
legibility ends up being subjective, there was a time when no one thought such a thing readable. And more readable is not, is more cute, in some scenarios makes little difference and precisely why I prefer what is more obvious, for me readable is to show what you do and not hide, unless it is minor detail. In most situations it even gets shorter, there are cases that is bad or impractical, not to mention performance. Why use two forms if one does the job well? Why keep key? For me legible is what you always do.
– Maniero