Search code examples
javascriptcoercion

Why JS doesn't coerce the value of i in a "for in loop"?


Given the two functions (with the expected output of //d):

function fearNotLetter(str) {

  for (let i = 0; i < str.length; i++) {
    let code = str.charCodeAt(i)
    if (code !== str.charCodeAt(0) + i) {
      return String.fromCharCode(str.charCodeAt(0) + i)
    }
  }
  return undefined
}

fearNotLetter("abce");

// d

And

function fearNotLetter(str) {

  for (let i in str) {
    let code = str.charCodeAt(i)
    if (code !== str.charCodeAt(0) + i) {
      return String.fromCharCode(str.charCodeAt(0) + i)
    }
  }
  return undefined

}

fearNotLetter("abce");

// ϊ

I discovered that the value of i is coerced to a String using the for...in loop. In my understanding, the if statement fails, because the value of i is no longer a number, therefore the sum can't be done. My question is, why doesn't JS coerce i back to a number in the if statement (str.charCodeAt(0) + i )? And allow the sum to be done the same way as he for...loop? Is it because, once iis coerced inside the funct, then it can't be coerced again?


Solution

  • In the first function you set the type of i to number when you initialized it to a number. In the second function i is a key to an iterable so it means it's type is string. There hasn't been type conversion at all.