Swap variables

3 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Array Destructuring

JS · Variables & Constants
syntax
const [a, b, ...rest] = array;
example
const rgb = [30, 120, 255];
const [red, green, blue] = rgb;
console.log(green);

const [first, , third] = ["a", "b", "c"];
console.log(first, third);
output
120
"a" "c"

Note Use commas to skip elements. Works with any iterable, not just arrays.

Variable Swapping

JS · Variables & Constants
syntax
[a, b] = [b, a];
example
let x = "hello";
let y = "world";
[x, y] = [y, x];
console.log(x, y);
output
"world" "hello"

Note No temporary variable needed. Works with any number of variables: [a, b, c] = [c, a, b];

PYPython

Multiple Assignment

PY · Variables & Types
syntax
a, b, c = val1, val2, val3
example
x, y, z = 10, 20, 30
first, *rest = [1, 2, 3, 4, 5]
print(first, rest)
output
1 [2, 3, 4, 5]

Note The starred variable (*rest) captures remaining items as a list. Only one starred variable is allowed per assignment.