1

I'm reading some algorithms to try and understand permutations in javascript, and the following one quite stunned me

var permArr = [], usedChars = [];
function permute(input) {
  var i, ch, chars = input.split('');
  for (i = 0; i < chars.length; i++) {
    ch = chars.splice(i, 1);
    usedChars.push(ch);
    if (chars.length == 0) permArr[permArr.length] = usedChars.join('');
    permute(chars.join(""));
    chars.splice(i, 0, ch);
    usedChars.pop();
  }
  return permArr
}

FYI I found this algorithm on the following website: http://staff.roguecc.edu/JMiller/JavaScript/permute.html

I can see that this algorithm works, but there is a line that confuses me and I can't find anywhere where it works

var i, ch, chars = input.split("");

If i console.log(i) or console.log(ch) before OR after in the code, it returns undefined everywhere. If i remove i and ch, the algorithm does not work anymore.

Can someone explain me this line and how it works? Thanks a lot

El-Cortez
  • 113
  • 1
  • 11
  • 1
    The line that confuses you has a name: "Javascript multiple left-hand assignment". Also you're confused about the subtle differences between `var x = 'blah';` and `x = 'blah'`. Helpful link to explain that difference: http://stackoverflow.com/a/1471738/445131 It has to do with the scope of the variable being created and destroyed inside the for loop, or persisting through every iteration. To see this, print out ch on every iteration of the loop. Defining ch inside or outside the loop has significance. – Eric Leschinski Feb 06 '17 at 15:39

1 Answers1

3

No Magic involved

var i, ch, chars = input.split('');

declares the variables i, ch and chars and assigns to chars what input.split('') returns.

Basically its equivalent to

var i; // undefined
var ch; // undefined
var chars = input.split(''); // Array of string

This is typically done for the variables to be available across loop iterations (to access previous values).

However...

i is just the loop varible and could be declared inline as in

for (var i = 0; i < chars.length; i++) {

ch could live inside the loop since it is reassigned in the first statement anyway

  for (var i = 0; i < chars.length; i++) {
      var ch = chars.splice(i, 1);

which makes the example confusing indeed (one could say it's poorly written)

nozzleman
  • 9,529
  • 4
  • 37
  • 58
  • Thanks a lot for your answer, but then, why does the algorithm not work anymore when i remove these two? – El-Cortez Feb 06 '17 at 15:40