El-Cortez El-Cortez - 4 years ago 134
Javascript Question

Javascript Permutations magic trick

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);
if (chars.length == 0) permArr[permArr.length] = usedChars.join('');
chars.splice(i, 0, ch);
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

Answer Source

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).


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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download