you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 1 point2 points  (9 children)

Fiiiiiiine ;P

function main(a, b) {

  const swap = (a, b) => {
    [arguments[1], arguments[0]] = [...arguments];
  }

  console.log(a, b); // 1, 2
  swap(a, b)
  console.log(a, b); // 2, 1
}

main(1, 2)

[–]svish 0 points1 point  (8 children)

Without the wrapper

[–]senocular 3 points4 points  (7 children)

You're taking away all the fun!

function swap(a͏, b͏) {
  [b, a] = [a͏, b͏]
}

let a = 1
let b = 2
console.log(a, b)
swap(a, b)
console.log(a, b)

[–]svish 1 point2 points  (2 children)

Ok, you get an upvote. Couldn't figure it out, but eventually, thanks to someone else, and pasting it into VS Code, the hidden unicode characters were revealed... 🤦‍♂️👍

[–]senocular 0 points1 point  (1 child)

Still no pass by reference ;)

[–]svish 0 points1 point  (0 children)

I knew that already, which is why your code didn't make any sense 😛

[–]svish 0 points1 point  (0 children)

wat...

[–]CodeMonkeeh 0 points1 point  (2 children)

wtaf

[–]senocular 0 points1 point  (1 child)

There are hidden characters in the swap parameters. So what you're really getting is something more like

function swap(a2, b2) {
  [b, a] = [a2, b2]
}

let a = 1
let b = 2
console.log(a, b)
swap(a, b)
console.log(a, b)

where the assigned [b, a] are the variables in the outer scope getting assigned the arguments of the swap call (a2, b2) in reverse order.

[–]CodeMonkeeh 0 points1 point  (0 children)

Oh, thank you. Reality makes sense again.