Why do I get an error with const howManyLetters = ( ) => { functions

Question:

Why does this code not print out numbers?
Repl link:

Auth

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())

I don’t know if this is defined or not.

This isn’t defined for sure.

So it’d be logging JSON (maybe [Object Object]), not just the number.

4 Likes

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.

3 Likes

Well, I think it should be new Number not Number(), and I’m quite sure you should use parseInt() instead.

1 Like

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:

Uncaught ReferenceError: Index is not defined

or

undefined
undefined
...
undefined
{ result: undefined }

Hope this helps! :upside_down_face:

1 Like

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.

1 Like