const howManyLetters = () => {
const phrase = 'Hey, can you go to the store with me?'
// counter
let result = 0;
for (const index in phrase) {
console.log(Number(index) + 1)
result = Index
}
return {result: result}
}
console.log(howManyLetters())
Number is the constructor for numbers, if you pass in a string that contains a number, it will be converted to a number, otherwise all truthy/falsy values will be converted to 1/0.
Just making Index lowercase as it is defined seems to fix the issue: index.
Hiya @eugerald05! So let’s run through the code together. Line 1-7 seems fine, so let’s jump ahead.
Line 8
console.log(Number(index) + 1)
From this, we know that index is equal to the index that we are at when cycling through the string phrase. When we add one to it, it should log to the console its’ index plus one. However, here, the more viable option would be parseInt(index) to parse it into an integer.
Line 9
result = Index
Here, we see how Index is capitalized, while in the line before, it is not. This should result in an error, since Index is not defined, or result becomes undefined.
Line 12
return {result: result}
Here, we return result in an object. However, there is a much more simple way to do this; {result}. This is the equivalent of {result: result}.
Line 14
console.log(howManyLetters());
This line logs the object we returned. In the end, we should have either logged to the console:
Either works, parseInt is essentially the same, but it wouldn’t work for decimals so you might want to use parseFloat. Number does both, you can also just use + in front of a value which achieves the same thing. Number doesn’t require new because it is actually a function rather than an ES6 class.