LESSON 20 · BEGINNER4 min read

Destructuring, Spread & JSON

Unpack data cleanly, copy structures deliberately, and parse JSON without crashing.

ES2024 / Node.js 20+Free to readModule 4 of 19
YOUR NEXT SMALL WINS

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.

destructure.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

spread.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

json-round-trip.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

safe-parse.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

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.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

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.

01

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.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
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.

02

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.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
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.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01In const [head, ...tail] = items, what does ...tail represent?
02What happens to an object property whose value is undefined during JSON.stringify?
03What is the safest response to JSON.parse on input from a file or network request?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

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.

EXPECTED OUTPUT
Order 7 for Ada: $42
Order 8 for guest: $0
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

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.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.