Search code examples
javascriptfor-loopfor-in-loop

Is for (let i in string) {} equivalent to for (let i = 0; i < string.length; i++) {}?


I have two pieces of code I wrote, I suppose they should work the same. As you may notice the only thing which is different between the two is the declaration of the for-loop.

Why is the code with for-in not working as expected?

Thanks in advance.

const allPermutations1 = s => {
     let permutations = []

     const recursion = (s, p = '') => {

         if (s.length === 0) return permutations.push(p)

         for (let i = 0; i < s.length; i++)
             recursion(s.slice(0, i) + s.slice(i+1), p + s[i]) 
     }

     return (recursion(s), permutations)
 }

allPermutations1('123') // ["123", "132", "213", "231", "312", "321"]

const allPermutations2 = s => {
    let permutations = []

    const recursion = (s, p = '') => {

        if (s.length === 0) return permutations.push(p)

        for (let i in s)
            recursion(s.slice(0, i) + s.slice(i+1), p + s[i]) 
    }

    return (recursion(s), permutations)
}

allPermutations2('123') // ["123", "132", "21", "312", "321"]

Solution

  • A for...in loop iterates over keys and returns a string. When you apply the i+1 iterator inside the splice, you are returning a string concatenation instead of incrementing the value. E.g '1' + '2' is '12' instead of 3. This situation may cause problems when splicing the numbers properly. You need to parse the key to a number for performing the operation as expected.