DEV Community

Discussion on: 30 JavaScript Tricky Hacks

Collapse
 
xi_sharky_ix profile image
shArky

Simply note, that #21 is more readable (for me both is good), but not easier for PC.
In case of XOR swap we working with numbers as bits represented in memory. In case of array swap we created 2 arrays.

Collapse
 
joolsmcfly profile image
Julien Dephix

You're right but it only creates one array actually: a temp array [b, a].
JS then destructures it to assign values to a and be respectively.

This is what code looks like after being transpiled:

    var a = 12;
    var b = 13;
    var _b;
    _b = [b, a], a = _b[0], b = _b[1];
Enter fullscreen mode Exit fullscreen mode

Yes, it uses more memory but we're talking about 2 numbers here so the diff in memory footprint is very minimal and not worth loosing readability.