Destructuring, Spread & JSON
Unpack data cleanly, copy structures deliberately, and parse JSON without crashing.
By the end, you’ll be able to…
- Destructure arrays and objects with defaults, renaming, and rest patterns.
- Distinguish rest from spread and explain shallow copying.
- Serialize and parse JSON while handling invalid text and unexpected shapes.
01Unpack data by shape
Destructuring assigns values from arrays or objects to names in one statement. Array patterns use position: const [first, second] = items. Object patterns use key names: const { title, done } = task. The original value is not changed; you are creating new bindings. The pattern reads like the data it describes, which is why it appears so often in function parameters and imports.
Object destructuring supports renaming and defaults: const { title: label, done = false } = task. A default applies when the property is undefined, not when it is null. Nested patterns can go several levels deep, but two levels is usually enough before the code becomes harder to read.
02Rest collects; spread expands
The same three-dot token means different things by position. In a pattern, rest collects remaining values: const [head, ...tail] = items. In a function parameter list, rest collects arguments into an array. In an expression, spread expands an iterable or object into a new literal or call. Spread in a call, format(...values), passes each item as a separate argument rather than one array.
Spread copies own enumerable properties, and it is shallow. const copy = { ...task } protects the top level of task, but copy.tags still points to the same array. Copy the nested value too when independence matters. For arrays, [...items] is a quick shallow copy.
03JSON is text, not a live object
JSON is a text format for exchanging data. JSON.stringify turns a supported JavaScript value into a string; JSON.parse turns that string back into values. JSON looks like JavaScript object syntax, but it is stricter: keys and strings need double quotes, and comments and trailing commas are not allowed.
JSON supports objects, arrays, strings, finite numbers, booleans, and null. Functions, undefined, and symbols disappear from objects or become null in arrays. Dates become ISO strings, NaN and Infinity become null, and circular references throw. A round trip is therefore not a general-purpose deep clone. Parse once at the boundary of your program, then work with ordinary objects inside.
04Handle parse errors and wrong shapes
JSON.parse throws a SyntaxError when the text is malformed. Wrap the call in try...catch when the input comes from a file, local storage, or a network response. Do not catch and ignore the error; return a clear fallback or rethrow with context so the failure can be fixed. A caught error can carry the original input and a message that names the expected format.
Valid JSON can still have the wrong shape. After parsing, check that the result is the type you expect before using it. A parsed array is not a task object, and a parsed number is not a list. Validate the fields you rely on, then build a clean object with only the properties your program supports. A fallback value only helps if the caller knows how to handle it.
The ideas worth keeping.
- Destructuring names values by position or key, with defaults and renaming for clarity.
- Rest collects values into an array; spread expands values into a new array, object, or call.
- JSON is strict text, so parse errors and shape checks belong at the boundary of the program.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Destructure an order
Write describeOrder that accepts an order object and destructures id, a nested customer name with a default of 'guest', and total with a default of 0. It should return a sentence such as Order 7 for Ada: $42. Test a full order and one with only an id.
Explore a worked solution
function describeOrder({ id, customer: { name = 'guest' } = {}, total = 0 } = {}) { return 'Order ' + id + ' for ' + name + ': $' + total;}console.log(describeOrder({ id: 7, customer: { name: 'Ada' }, total: 42 }));console.log(describeOrder({ id: 8 }));The nested pattern destructures customer only when it exists; the = {} default prevents a missing customer from throwing. The name and total defaults fill in gaps. The output is Order 7 for Ada: $42 and Order 8 for guest: $0.
Exercise 2: Parse a task safely
Write safeParseTask(text) that returns a clean task object with id, title, and done, or null when the text is invalid or the shape is wrong. Validate that id is an integer, title is a string, and done is a boolean. Test valid JSON, an id stored as a string, and malformed text.
Explore a worked solution
function safeParseTask(text) { try { const value = JSON.parse(text); if (!value || typeof value !== 'object' || Array.isArray(value)) { return null; } if (!Number.isInteger(value.id) || typeof value.title !== 'string') { return null; } if (typeof value.done !== 'boolean') { return null; } return { id: value.id, title: value.title, done: value.done }; } catch { return null; }}console.log(safeParseTask('{"id":2,"title":"Write tests","done":true}'));console.log(safeParseTask('{"id":"2","title":"Write tests","done":false}'));console.log(safeParseTask('not json'));The try block handles malformed text, while the type checks handle valid JSON with the wrong shape. Returning a new object ensures only the three supported properties escape the parser. The first call returns the task; the other two return null.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Destructure an order
Write describeOrder that accepts an order object and destructures id, a nested customer name with a default of 'guest', and total with a default of 0. It should return a sentence such as Order 7 for Ada: $42. Test a full order and one with only an id.
Order 7 for Ada: $42 Order 8 for guest: $0
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.