Problem with splice

function permAlone(str) {
  var combos = [];
  var num = 0;
  var options;
  str = str.split("");
  for(i=0;i<str.length;i++){
    options = str;
    console.log(options);
    options.splice(i,1);
  }
  console.log("Next!");
  return num;
}

For some reason options doesn’t change back to str after each iteration. What am I missing?

That is because the following line assigns a reference to an array.

str = str.split("");

When the above code executes with the call permAlone(‘aab’), str gets assigned a reference (not the actual array) to [‘a’, ‘a’, ‘b’]. Inside your for loop, when you write options = str, you are just assigning the same reference to [‘a’, ‘a’, ‘b’] to options. Then when you write options.splice(i,1), the splice mutates the array referenced by options (which is the same array referenced by str). If you want to create a shallow copy of the str array inside the for loop, you would need to use slice as follows:

options = str.slice(); // creates a reference to a new array that looks the same as str
1 Like

You’re not assigning it to str.