I’m a novice in Javascript and I was stuck in a leetcode question due to the js syntax, which involves swapping two elements in an array. The complete code in JS is shown below:
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
const n = nums.length
const rs = []
const dfs_swap = (idx, path) => {
if (idx >= n - 1) {
rs.push([...path])
return
}
for (let i = idx; i < n; i++) {
[path[i], path[idx]] = [path[idx], path[i]]
dfs_swap(idx + 1, path)
[path[i], path[idx]] = [path[idx], path[i]]
}
}
dfs_swap(0, [...nums])
return rs
};
// test case below
permute([1,2,3])
But I received the an runtime error below:
Line 17 in solution.js
[path[i], path[idx]] = [path[idx], path[i]]
^
TypeError: Cannot set properties of undefined (setting '2')
Line 17: Char 34 in solution.js (dfs_swap)
Line 16: Char 13 in solution.js (dfs_swap)
Line 21: Char 5 in solution.js (permute)
Line 35: Char 19 in solution.js (Object.<anonymous>)
Line 16: Char 8 in runner.js (Object.runner)
Line 24: Char 26 in solution.js (Object.<anonymous>)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Module.load (node:internal/modules/cjs/loader:1207:32)
at Module._load (node:internal/modules/cjs/loader:1023:12)
Node.js v20.10.0
I was using the debugger to look into the code at runtime and found everything looked fine there before getting that runtime error. I even tried to run this in my Chrome’s developer console but ended up with the same error.
Then, I only added one thing to solve this error: I added a semicolon after dfs_swap(idx + 1, path), that is:
for (let i = idx; i < n; i++) {
[path[i], path[idx]] = [path[idx], path[i]]
dfs_swap(idx + 1, path);
[path[i], path[idx]] = [path[idx], path[i]]
}
After this, I was even more confused about this and ChatGPT failed to give me a plausible answer for that. I pretty much appreciate any help or insights on this, and thank you in advance!

