Question about splicing arrays

I’m playing around with code a bit to understand splicing better. Do you know why repl.it is throwing an error when I run this code:

function splicing(str) {
  let arr = str.split('');
  for(let i = 0; i < arr.length; i++) {
    if(arr[i] === 'T') {
      arr.splice(i,0,'S');
    }
  }
  return arr;
}
splicing('ThisIsSpinalTap');

It’s sending this message:

RangeError: Potential infinite loop. You can disable this from settings.
    at spinalCase:3:102
    at eval:10:1
    at eval
    at new Promise

You have created an infinite loop, because during each iteration of the for loop, arr[i] will be ‘T’ because you keep inserting an ‘S’ at the ith index which shifts the ‘T’ at the start of the original ‘ThisIsSpinalTap’ to the right one character in sync with i.

After first iteration, arr is

[ 'S'  'T', 'h', 'i', 's', 'I', s', 'S', 'p', 'i', 'n', 'a', 'l', 'T', 'a', 'p' ]

After second iteration, arr is

['S', 'S'  'T', 'h', 'i', 's', 'I', s', 'S', 'p', 'i', 'n', 'a', 'l', 'T', 'a', 'p' ]

After third iteration, arr is

['S', 'S', 'S'  'T', 'h', 'i', 's', 'I', s', 'S', 'p', 'i', 'n', 'a', 'l', 'T', 'a', 'p' ]

and so on

1 Like