Destructuring Assigns Defaults And Rest

Destructuring pulls values out with defaults for missing slots and rest for leftovers, covering arrays, objects, swaps, and function parameters.

JavascriptData Fetching

Code

javascriptsnippet
24 lines
// 数组解构:缺位补默认值,余项收进 rest 数组
const [first, second = 'fallback', ...rest] = ['alpha', undefined, 'gamma', 'delta'];
console.log('first:', first);
console.log('second:', second);
console.log('rest:', rest);

// 对象解构:默认值同样生效,剩余键收进 rest 对象
const { host, port = 8080, ...options } = { host: 'api.example.com', timeout: 2500, protocol: 'https' };
console.log('host:', host);
console.log('port:', port);
console.log('options:', options);

// 经典用途:交换两个变量
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log('swapped:', a, b);

// 函数参数解构 + 默认值:连实参缺席都能兜住
function connect({ host: h = 'localhost', port: p = 443 } = {}) {
  return h + ':' + p;
}
console.log('connect:', connect());
console.log('connect:', connect({ host: 'api.example.com', port: 8443 }));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

first: alpha
second: fallback
rest: [ 'gamma', 'delta' ]
host: api.example.com
port: 8080
options: { timeout: 2500, protocol: 'https' }
swapped: 2 1
connect: localhost:443
connect: api.example.com:8443

How it works

Destructuring Assigns Defaults And Rest is built around the function connect.

Applying it

Entry signature: function connect({ host: h = 'localhost', port: p = 443 } = {})

The run emits 8 labeled sections — first:, second:, rest:, host:, port:, options:, swapped:, connect: — one per step.

Statements that matter

return h + ':' + p;

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `connect` at load time.