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.

Frequently asked questions

How does JavaScript handle swap variables?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Array Destructuring" snippet in JavaScript uses `const [a, b, ...rest] = array;`.
Which code does the JavaScript example use?
The "Array Destructuring" snippet uses `const [a, b, ...rest] = array;`, from the Variables & Constants section of the JavaScript cheat sheet.
Which stacks cover "swap variables" on this page?
JavaScript, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Array Destructuring": Use commas to skip elements. Works with any iterable, not just arrays.