The first problem is that you are not returning anything from the function vezesLetraAparece
. Note that there is no statement return
in the body of the function and, because of this, it at all times will return undefined
.
Therefore by placing a return
to return the value of resultado
after the loop for
finish, we’ll have something like this:
function vezesLetraAparece(frase, letra) {
var resultado = [];
for (var letra = 0; letra < frase.length; letra++) {
resultado.push (frase[letra]);
}
return resultado;
}
console.log(vezesLetraAparece('abcaba', 'a'));
But by executing the code, we realize there’s another mistake. The code is not actually returning the number of times the letter passed in the 2nd argument occurs in the string. The for
is simply splitting the string into an array, each element being a character.
Therefore, it is perceived that using an array as a result (or accumulator), in this case, does not make much sense. You also have to check if the letter corresponding to the current iteration matches (is equal) to the one that interests us. You’re not doing that check either.
Anyway, we need to use a number (which we will start as 0
) as an accountant and a declaration if
to count only the letters that are equal to the one we seek.
We will then:
function vezesLetraAparece(frase, letra) {
var resultado = 0;
for (var indiceLetra = 0; indiceLetra < frase.length; indiceLetra++) {
if (frase[indiceLetra] === letra) {
resultado++; // Somamos 1 ao contador.
}
}
return resultado;
}
console.log(vezesLetraAparece('abcaba', 'a')); // 3
Also note that I had to rename the variable letra
(in the for
) for indiceLetra
. If the name continued as letra
, we would be over-writing the parameter letra
, declared in function. This is called variable shadowing and in that case it is undesirable.
It also had an extra semicolon after for
. Like him prevents the block of the for
to be executed, we must remove it.
To simplify the for
a little (and, breaking, deal with a possible problem linked to the "decomposition" of certain Unicode characters), you can use a loop for..of
:
function vezesLetraAparece(frase, letra) {
var resultado = 0;
for (const letraAtual of frase) {
if (letraAtual === letra) {
resultado++;
}
}
return resultado;
}
console.log(vezesLetraAparece('abcaba', 'a')); // 3
Obviously there are several other ways to solve this problem. These are just two of countless possibilities. As you learn more about Javascript, you’ll be able to think of other ways to solve it. Nevertheless, they are probably the simplest. :)
Thanks friend for the explanation! I’m starting in Javascript now, some things are still hard to catch, but one day I get there and I get mad like you.
– Ulisses Souza