# Trying to understand how this function works (permutates an array)

Please see my questions in the log part.
Function:

``````const permutator = (inputArr) => {
let result = [];

const permute = (arr, m = []) => {
if (arr.length === 0) {
result.push(m)
console.log("result: " + result);
console.log("m: " + m);
} else {
for (let i = 0; i < arr.length; i++) {
console.log("i: " + i);
console.log("m in for loop: " + m);
console.log("result in for loop: " + result);
let curr = arr.slice();
console.log("curr: " + curr);
let next = curr.splice(i, 1);
console.log("next: " + next);
console.log("permute(curr, m.concat(next)): " + curr + " | " + m.concat(next));
permute(curr, m.concat(next))
}
}
}

permute(inputArr)

return result;
}
permutator(['c','a','t']);
``````

Log:

``````i: 0
m in for loop:
result in for loop:
curr: c,a,t
next: c
permute(curr, m.concat(next)): a,t | c
i: 0
m in for loop: c
result in for loop:
curr: a,t
next: a
permute(curr, m.concat(next)): t | c,a
i: 0
m in for loop: c,a
result in for loop:
curr: t
next: t
permute(curr, m.concat(next)):  | c,a,t
result: c,a,t
m: c,a,t
// It makes sense up to this point, arr.lenght === 0 so m is pushed to result
//So, 1. how does the code continue to the else statement?
//      2. how does m become equal to c?
//      3. how does curr become equal to a, t?
i: 1
m in for loop: c
result in for loop: c,a,t
curr: a,t
next: t
permute(curr, m.concat(next)): a | c,t
//     4. why does i reset to 0?
i: 0
m in for loop: c,t
result in for loop: c,a,t
curr: a
next: a
permute(curr, m.concat(next)):  | c,t,a
result: c,a,t,c,t,a
m: c,t,a
...
``````