Tuples & destructuring
A tuple is a small, fixed-size, immutable, ordered group of values - mainly useful as the thing you destructure into several variables at once.
Tuple literals
Two things about the literal syntax are easy to trip over, so they're called out explicitly here rather than left to be discovered by trial and error:
(x) is not a one-element tuple - it's just a parenthesized expression. A single-element tuple needs a trailing comma: (x,). And an empty tuple isn't () (that's a syntax error) - it's written (,,), with two commas.
let pair = (1, 2); // a genuine 2-tuple
let single = (5,); // a 1-tuple - note the trailing comma
let notATuple = (5); // typeof() is "number", not "tuple" - no trailing comma, so this is just `5`
let empty = (,,); // the empty tuple - yes, really
Indexing & size
Tuples support [index] reads and a .size property, same as arrays, but reject any attempt to change an element:
let t = (10, 20, 30);
output(t[0]); // 10
output(t.size); // 3
t[0] = 99; // runtime error: Cannot modify an immutable tuple
Destructuring
A tuple pattern of plain variable names on the left of = unpacks a same-shaped tuple on the right - in both a fresh declaration (let/const) and a plain assignment to variables that already exist:
let (a, b) = (1, 2);
output(a); // 1
output(b); // 2
// swapping two existing variables in one step:
let x = 1;
let y = 2;
(x, y) = (y, x);
output(x); // 2
output(y); // 1
Only plain variable names are allowed inside the pattern - you can't nest a tuple pattern inside another, or destructure directly into a struct field or array index. Declaring a single variable via destructuring still needs the 1-tuple's trailing comma on both sides:
let (only,) = (42,);
output(only); // 42