JavaScript Destructuring and Spread Syntax for Arrays and Objects

Destructuring pulls values out of arrays and objects into variables in one line, and spread copies and merges them. Together they make code shorter and clearer, and you see them everywhere in modern JavaScript: const { page } = ... in every Playwright test, { ...defaults, ...overrides } for test configuration, and [first, ...rest] for table rows. In this lesson you will learn every form of destructuring and spread, with defaults, renaming, nesting and the traps to avoid.

Advertisement

📖 What You’ll Learn: array destructuring, skipping items, defaults, the rest pattern, swapping variables, object destructuring, renaming, defaults for missing properties, nested destructuring, destructuring in function parameters and loops, spread for arrays (copy, merge, insert), spread for objects (copy, merge, override), shallow-copy limits, and practical test-data patterns.


📦 Array Destructuring

Definition: destructuring is a syntax that unpacks values from arrays (by position) or objects (by name) into separate variables.

📄 array.js

const point = [10, 20, 30];

// Without destructuring
const x1 = point[0];
const y1 = point[1];

// With destructuring
const [x, y, z] = point;
console.log(x1, y1, "|", x, y, z);

const [first, , third] = ["a", "b", "c"];   // skip an item with an empty slot
console.log(first, third);

const [one, two, extra] = [1, 2];           // missing items are undefined
console.log(one, two, extra);

⌨️ Terminal

node array.js

🖥️ Output

10 20 | 10 20 30
a c
1 2 undefined

Default values

📄 array-defaults.js

const [env = "qa", browser = "chromium", workers = 2] = ["staging"];
console.log(env, browser, workers);

const [a = 1] = [null];      // defaults apply only to undefined
console.log(a);

⌨️ Terminal

node array-defaults.js

🖥️ Output

staging chromium 2
null

The rest pattern

...name as the last item collects the remaining elements into a new array:

📄 array-rest.js

const [header, ...rows] = [
  ["Name", "Role"],
  ["Asha", "Tester"],
  ["Ravi", "Developer"],
];
console.log(header);
console.log(rows);

const [winner, ...others] = ["chromium", "firefox", "webkit"];
console.log(winner, others);

⌨️ Terminal

node array-rest.js

🖥️ Output

[ 'Name', 'Role' ]
[ [ 'Asha', 'Tester' ], [ 'Ravi', 'Developer' ] ]
chromium [ 'firefox', 'webkit' ]

Swapping variables

📄 swap.js

let left = "login";
let right = "logout";
[left, right] = [right, left];
console.log(left, right);

⌨️ Terminal

node swap.js

🖥️ Output

logout login

🗂️ Object Destructuring

Object destructuring takes properties by name, so order does not matter:

📄 object.js

const user = { id: 7, name: "Asha", role: "tester", city: "Pune" };

const { name, role } = user;
console.log(name, role);

const { city, id } = user;           // any order
console.log(id, city);

const { email } = user;              // missing property: undefined
console.log(email);

⌨️ Terminal

node object.js

🖥️ Output

Asha tester
7 Pune
undefined

Renaming and defaults

{ property: newName } stores the value under a different variable name, and = value sets a default for missing (undefined) properties. You can combine both:

📄 rename.js

const response = { status: 200, data: { items: [] }, headers: { "content-type": "application/json" } };

const { status: code, data: body } = response;
console.log(code, body);

const { timeout = 30000, retries: maxRetries = 2 } = { retries: 0 };
console.log(timeout, maxRetries);      // 0 is kept: defaults only replace undefined

const { "content-type": contentType } = response.headers;   // property names with dashes
console.log(contentType);

⌨️ Terminal

node rename.js

🖥️ Output

200 { items: [] }
30000 0
application/json
Advertisement

Rest in objects

📄 object-rest.js

const user = { id: 7, name: "Asha", password: "secret", token: "abc" };
const { password, token, ...safeUser } = user;   // remove sensitive fields
console.log(safeUser);

⌨️ Terminal

node object-rest.js

🖥️ Output

{ id: 7, name: 'Asha' }

💡 Tip: The rest pattern is a clean way to remove fields before logging or sending an object, such as stripping passwords and tokens from test logs.


🪆 Nested Destructuring

Patterns can mirror the shape of nested data:

📄 nested.js

const order = {
  id: 501,
  customer: { name: "Asha", address: { city: "Pune", pin: "411001" } },
  items: [
    { sku: "PEN-1", qty: 3 },
    { sku: "BOOK-9", qty: 1 },
  ],
};

const {
  id,
  customer: { name, address: { city } },
  items: [firstItem, ...otherItems],
} = order;

console.log(id, name, city);
console.log(firstItem.sku, otherItems.length);

⌨️ Terminal

node nested.js

🖥️ Output

501 Asha Pune
PEN-1 1

Note that customer and address are not created as variables here; they only describe the path. Only the names at the end of each path (name, city) become variables.

⚠️ Watch out: Destructuring a missing nested object throws. If customer could be missing, give it a default object: const { customer: { name } = {} } = order;.

📄 nested-missing.js

const order = { id: 502 };   // no customer
try {
  const { customer: { name } } = order;
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}
const { customer: { name = "Guest" } = {} } = order;
console.log(name);

⌨️ Terminal

node nested-missing.js

🖥️ Output

TypeError: Cannot read properties of undefined (reading 'name')
Guest

🔧 Destructuring in Parameters and Loops

Destructuring in a function’s parameter list is very common. It is the “options object” pattern from the Parameters lesson, and it is how Playwright passes fixtures into tests:

📄 params.js

function formatUser({ name, role = "viewer", address: { city } = {} }) {
  return `${name} (${role})${city ? " from " + city : ""}`;
}
console.log(formatUser({ name: "Asha", role: "tester", address: { city: "Pune" } }));
console.log(formatUser({ name: "Ravi" }));

// Playwright style: async ({ page, request }) => { ... }
const runTest = async ({ page, baseURL = "https://qa.example.com" }) => `${page} opened ${baseURL}`;
runTest({ page: "page#1" }).then(console.log);

⌨️ Terminal

node params.js

🖥️ Output

Asha (tester) from Pune
Ravi (viewer)
page#1 opened https://qa.example.com

In loops, destructure each element directly:

📄 loops.js

const results = [
  { test: "login", status: "passed", ms: 820 },
  { test: "cart", status: "failed", ms: 1430 },
];
for (const { test, status } of results) {
  console.log(test, status);
}

const config = { env: "qa", workers: 4 };
for (const [key, value] of Object.entries(config)) {
  console.log(`${key}=${value}`);
}

console.log(results.map(({ test, ms }) => `${test}:${ms}`));

⌨️ Terminal

node loops.js

🖥️ Output

login passed
cart failed
env=qa
workers=4
[ 'login:820', 'cart:1430' ]

Advertisement

🌊 Spread with Arrays

Definition: spread syntax ...value expands an iterable (such as an array, string or Set) into individual elements. It looks like rest, but appears where values are used, not where variables are declared.

📄 array-spread.js

const smoke = ["login", "search"];
const regression = ["refund", "export"];

const all = [...smoke, ...regression];          // merge
const copy = [...smoke];                         // shallow copy
const withExtra = ["setup", ...smoke, "teardown"];  // insert around
console.log(all, copy === smoke, withExtra);

console.log([..."QA"]);                          // string -> characters
console.log([...new Set([3, 1, 3, 2, 1])]);      // unique values
console.log(Math.max(...[12, 99, 45]));          // into function arguments

⌨️ Terminal

node array-spread.js

🖥️ Output

[ 'login', 'search', 'refund', 'export' ] false [ 'setup', 'login', 'search', 'teardown' ]
[ 'Q', 'A' ]
[ 3, 1, 2 ]
99

🧬 Spread with Objects

Object spread copies an object’s own properties into a new object. When the same key appears more than once, the last one wins, which makes spread perfect for “defaults plus overrides”:

📄 object-spread.js

const defaults = { browser: "chromium", headless: true, retries: 0, timeout: 30000 };
const ciOverrides = { retries: 2, workers: 4 };
const localOverrides = { headless: false };

const ciConfig = { ...defaults, ...ciOverrides };
const localConfig = { ...defaults, ...localOverrides };
console.log(ciConfig);
console.log(localConfig);

const user = { name: "Asha", role: "tester" };
const promoted = { ...user, role: "lead", since: 2026 };   // copy + change + add
console.log(user, promoted);

const wrongOrder = { role: "lead", ...user };             // user's role overwrites "lead"
console.log(wrongOrder.role);

⌨️ Terminal

node object-spread.js

🖥️ Output

{
  browser: 'chromium',
  headless: true,
  retries: 2,
  timeout: 30000,
  workers: 4
}
{ browser: 'chromium', headless: false, retries: 0, timeout: 30000 }
{ name: 'Asha', role: 'tester' } { name: 'Asha', role: 'lead', since: 2026 }
tester

⚠️ Watch out: Spread makes a shallow copy. Nested objects and arrays are still shared between the original and the copy. Changing copy.address.city also changes the original. Use structuredClone for a deep copy, or spread each nested level you change.

📄 shallow.js

const base = { name: "Asha", address: { city: "Pune" } };
const shallow = { ...base };
shallow.address.city = "Delhi";
console.log(base.address.city);              // changed!

const safe = { ...base, address: { ...base.address, city: "Mumbai" } };
console.log(base.address.city, safe.address.city);

⌨️ Terminal

node shallow.js

🖥️ Output

Delhi
Delhi Mumbai

🧪 Tester Scenario: Build Test Data Variations

A base valid user plus small overrides gives you every variation a form test needs, with each test showing only what is different:

📄 variations.js

const validUser = Object.freeze({
  firstName: "Asha",
  lastName: "Rao",
  email: "asha@sqatools.in",
  password: "Secret@123",
  address: Object.freeze({ city: "Pune", pin: "411001" }),
});

const build = (overrides = {}) => ({
  ...validUser,
  ...overrides,
  address: { ...validUser.address, ...overrides.address },
});

const cases = [
  ["valid user", build(), true],
  ["missing email", build({ email: "" }), false],
  ["short password", build({ password: "abc" }), false],
  ["invalid PIN", build({ address: { pin: "12" } }), false],
];

const isValid = ({ email, password, address: { pin } }) =>
  email.includes("@") && password.length >= 8 && /^\d{6}$/.test(pin);

for (const [name, data, expected] of cases) {
  const actual = isValid(data);
  console.log(`${actual === expected ? "PASS" : "FAIL"} ${name.padEnd(15)} city=${data.address.city} pin=${data.address.pin}`);
}
console.log("base untouched:", validUser.address.pin);

⌨️ Terminal

node variations.js

🖥️ Output

PASS valid user      city=Pune pin=411001
PASS missing email   city=Pune pin=411001
PASS short password  city=Pune pin=411001
PASS invalid PIN     city=Pune pin=12
base untouched: 411001
  • Object.freeze makes accidental changes to the base data impossible.
  • build merges overrides over the base and also merges the nested address, so overriding only pin keeps the city.
  • The validator destructures exactly the fields it needs, directly in its parameter list.

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Destructure ["2026", "11", "23"] into year, month and day, and print 23/11/2026.

Show answer

📄 practice1.js

const [year, month, day] = "2026-11-23".split("-");
console.log(`${day}/${month}/${year}`);

🖥️ Output

23/11/2026

Q2. From { status: 404, statusText: "Not Found", body: null }, take status as code and statusText as message, and print them.

Show answer

📄 practice2.js

const res = { status: 404, statusText: "Not Found", body: null };
const { status: code, statusText: message } = res;
console.log(code, message);

🖥️ Output

404 Not Found

Q3. Write describe({ name, tags = [] }) that returns "name [tag1, tag2]" or "name [no tags]".

Show answer

📄 practice3.js

function describe({ name, tags = [] }) {
  return `${name} [${tags.length ? tags.join(", ") : "no tags"}]`;
}
console.log(describe({ name: "login", tags: ["smoke", "auth"] }));
console.log(describe({ name: "export" }));

🖥️ Output

login [smoke, auth]
export [no tags]

Q4. Remove the password field from { user: "asha", password: "x", role: "tester" } without changing the original object.

Show answer

📄 practice4.js

const account = { user: "asha", password: "x", role: "tester" };
const { password, ...publicAccount } = account;
console.log(publicAccount, account);

🖥️ Output

{ user: 'asha', role: 'tester' } { user: 'asha', password: 'x', role: 'tester' }

Q5. Merge { retries: 0, workers: 1 } with { workers: 4, reporter: "html" } so the second object wins on conflicts.

Show answer

📄 practice5.js

const base = { retries: 0, workers: 1 };
const ci = { workers: 4, reporter: "html" };
console.log({ ...base, ...ci });

🖥️ Output

{ retries: 0, workers: 4, reporter: 'html' }

Q6. Get the city from const data = { user: { profile: { address: { city: "Pune" } } } } with one nested destructuring statement.

Show answer

📄 practice6.js

const data = { user: { profile: { address: { city: "Pune" } } } };
const { user: { profile: { address: { city } } } } = data;
console.log(city);

🖥️ Output

Pune

🧠 MCQ Quiz: Destructuring and Spread

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is b after const [a, b] = [10, 20, 30];?
  2. What is rest after const [x, ...rest] = [1, 2, 3];?
  3. How do you rename while destructuring { status } into a variable called code?
  4. What is t after const { t = 5 } = { t: null };?
  5. How do you swap a and b?
  6. What is { ...{ a: 1, b: 2 }, b: 3 }?
  7. Is { ...obj } a deep copy?
  8. What happens with const { a: { b } } = {};?
  9. What does [...new Set([1, 1, 2])] produce?
  10. In test("x", async ({ page }) => ...), what is { page }?

💼 Interview Questions and Answers

Q1. What is the difference between the rest and spread syntax?

Both use .... Rest collects multiple values into one: in function parameters (function f(...args)) and in destructuring patterns (const [first, ...others] = arr). Spread expands one iterable or object into many: in function calls (f(...arr)), array literals ([...a, ...b]) and object literals ({ ...obj }).

Q2. How does object spread handle duplicate keys and nested objects?

Properties are copied left to right, so for duplicate keys the last one wins; this is why { ...defaults, ...overrides } works. The copy is shallow: nested objects are copied by reference, so changing them through the copy also changes the original. Spread nested levels explicitly or use structuredClone for deep copies.

Q3. Predict the output.

📄 predict.js

const { a = 1, b = 2, c = 3 } = { a: undefined, b: null };
const [x = 10, y = x * 2] = [];
console.log(a, b, c, x, y);

⌨️ Terminal

node predict.js

🖥️ Output

1 null 3 10 20

Defaults apply to undefined (a and the missing c), not to null, so b stays null. Defaults can refer to earlier variables, so y is x * 2 = 20.

Q4. How would you use destructuring and spread to manage test configuration?

Keep a frozen object of defaults, merge environment-specific overrides with spread ({ ...defaults, ...envConfig, ...cliOverrides }), and destructure only the needed settings in helpers (function launch({ browser, headless = true })). Strip secrets before logging with a rest pattern (const { password, ...safe } = config). This keeps every test explicit about what it changes.


Advertisement

❓ Frequently Asked Questions

🤔 Can I destructure a function’s return value?

Yes, and it is a common way to return several values: const { min, max } = stats(list); or const [data, error] = await safeCall();.

🤔 Does destructuring copy objects?

No. Destructured variables hold the same values; if a value is an object, the variable refers to the same object.

🤔 Can I spread an object into an array?

Not directly; plain objects are not iterable. Use Object.values(obj), Object.keys(obj) or Object.entries(obj) and spread that.

🤔 What happens if I destructure null or undefined?

It throws a TypeError (“Cannot destructure property … of undefined”). Give the source a default, for example function f({ a } = {}) or const { a } = obj ?? {}.


🏁 Summary

  • Array destructuring unpacks by position; object destructuring unpacks by name.
  • Use name: newName to rename, = value for defaults (undefined only), and ...rest to collect the remainder.
  • Nested patterns mirror nested data; give optional nested objects a default = {}.
  • Spread copies and merges arrays and objects; for duplicate keys the last one wins.
  • Spread copies are shallow: use structuredClone or spread nested levels to avoid shared changes.

Next, continue with Lesson 32: Sorting and Searching Arrays.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in