xSKILLby Infirals
Register

JavaScript for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Destructuring, spread and JSON

Objects, arrays and data14 min readLesson 3 of 4

3.1 Destructuring objects

Destructuring is a declaration pattern that pulls properties out of an object and assigns them to names. The braces on the left match the shape of the object, and each name asks for the property with the same key. It removes a run of user.name, user.city style assignments.

Aliases rename a property on the way out: const { score: marks } = user puts the score under the name marks. Defaults fill a missing or undefined property: const { theme = "light" } = settings. A default does not replace null.

javascript
const user = { name: "Aarav", city: "Delhi", score: 88 };
const { name, score: marks } = user;
const [first, second] = ["pen", "book", "bag"];

console.log(name);
console.log(marks);
console.log(first);
console.log(second);

Output

Aarav
88
pen
book

Array destructuring follows position instead of key. The first name gets index 0, the second gets index 1, and a rest element can gather the remainder. Ellipsis in the parameter list of a function is the same rest idea.

Destructuring is common in function parameters. A function that takes an options object can declare the properties it needs in the parameter list, which documents the shape and gives a default in one place.

javascript
const settings = { theme: "light" };
const { theme, fontSize = 16 } = settings;

function createButton({ label, disabled = false }) {
  return `${label}:${disabled}`;
}

console.log(theme);
console.log(fontSize);
console.log(createButton({ label: "Save" }));

Output

light
16
Save:false

3.2 Spread copies and merges

The spread operator ... expands an iterable into individual values. In an array literal it copies the items, and in an object literal it copies the properties. Later values win, so { ...base, fontSize: 20 } copies base and then overrides fontSize.

Spread performs a shallow copy. Nested objects and arrays are still shared references, so changing a nested value through the copy changes the original. For a deep copy of plain data, structuredClone is the modern tool; for data from JSON, a parse-stringify round trip also produces a new graph.

Spread in a function call passes array items as separate arguments: Math.max(...numbers). This is convenient and expensive on very large arrays, where apply or a loop is safer.

javascript
const base = { theme: "light", fontSize: 16 };
const custom = { ...base, fontSize: 20 };
const list = [1, 2];
const next = [...list, 3];

console.log(custom.fontSize);
console.log(JSON.stringify(next));
console.log(base.fontSize);

Output

20
[1,2,3]
16

3.3 Rest in destructuring

The rest element collects the remaining items into a new array or the remaining properties into a new object. It must come last, and it produces a plain array or object rather than the original type.

Rest and spread look identical and do opposite jobs. Spread breaks a collection into pieces; rest gathers pieces into a collection. The position tells you which is happening: rest appears in a binding or parameter list, spread appears where values are being constructed.

3.4 JSON

JSON is a text format for data interchange. It supports objects, arrays, strings, numbers, booleans and null. It does not support undefined, functions, dates or cycles. JSON.stringify turns a value into text, and JSON.parse turns text back into a fresh object graph.

The round trip drops what JSON cannot represent. A function property disappears, undefined properties disappear, and a Date becomes a string after a stringify-parse cycle. When sending data to an API, check that the shape survives the format.

JSON string keys use double quotes, and trailing commas are not allowed. The parsed value is ordinary JavaScript data with no methods, so code that expects the original object's class must rebuild it.

javascript
const user = { name: "Aarav", active: true };
const text = JSON.stringify(user);
const back = JSON.parse(text);

console.log(text);
console.log(back.name);
console.log(typeof text);

Output

{"name":"Aarav","active":true}
Aarav
string

3.5 Destructuring in loops and function calls

Destructuring works wherever a value is bound: in a loop header, in a function parameter, and in a catch clause for an error object. for (const [id, name] of entries) pulls each pair apart without an index variable, and function draw({ x, y }) documents that the function needs a point.

Array destructuring can swap two names in one statement: [first, second] = [second, first]. The right side is evaluated first, so the old values land in the correct names. This trick is common in sorting and state updates.

3.6 Spread in function calls

Spreading an array into a call passes its items as separate arguments. Math.max(...numbers) finds the maximum of a list without a loop, and console.log(...values) prints each value as its own argument. The array must not be enormous, because a very long argument list can exceed the engine's limit.

The same syntax works for building a new array from an existing one plus extra items. const next = [...items, newItem] is the immutable version of push, which is why state managers and React code use it constantly. The original array stays untouched.

3.7 JSON errors

JSON.parse throws a SyntaxError when the text is not valid JSON, and the error message points at the position where parsing failed. Wrap parsing of external text in try and catch so one bad response does not stop a whole page.

A common failure is a response that is already an object because a test mocked it, or text that uses single quotes and trailing commas from hand-written JavaScript. Validate the input shape after parsing: the JSON might be valid and still not be the object the code expected.

JSON.stringify throws on circular references, where an object eventually points back at itself. It also silently drops undefined and function values. Check both directions when a data pipeline behaves strangely.

3.8 Copy semantics in state updates

Modern interfaces treat state as read-only and build a new value for every change. Spread makes that style practical: copy the record, override the changed field, and pass the copy to the render function. The old record stays valid for comparison and for undo.

Do the same one level down when a nested field changes. Copy the outer object and the nested object that changes, then override the leaf. Skipping the inner copy mutates shared state and hides the change from any code that compares old and new references.

This copying discipline is the reason spread appears in every modern JavaScript codebase, and it is also why nested state can become expensive. Keep state flat when the interface allows it, and the copies stay small.

3.9 Common mistakes

  • Destructuring a property that does not exist and getting undefined.
  • Forgetting that a default only applies to undefined, not null.
  • Expecting spread to deep copy nested data.
  • Putting the rest element anywhere except last.
  • Calling JSON.parse on a string that is not valid JSON.
  • Losing undefined values, functions or dates through a JSON round trip.

Exam

Destructuring questions usually print the destructured names, not the original object. Match names to keys, apply defaults only for undefined, and remember that spread copies one level. For JSON questions, follow the type: string in, object out after parse.

  • Destructure two properties from an object and rename one.
  • Use array destructuring to swap two variables.
  • Merge two objects with spread and override one property.
  • Stringify an object, parse it back and compare the two shapes.