Codiqo

Learn JavaScript · lesson 35 of 60 · about 8 minutes

Destructuring, Spread and JSON

Load Sam's saved settings from JSON with defaults, and share the profile card as JSON using spread.

What you'll learn

  • Destructure arrays and objects
  • Copy and merge with spread
  • Use JSON.stringify and JSON.parse

Saved settings

Browsers and servers store and send data as text, so Sam's settings arrive as JSON text, like {"theme":"dark"}. JSON.parse turns it back into an object, and destructuring with defaults unpacks the theme and text size in one line, filling in anything that was never saved. Going the other way, JSON.stringify turns the profile card into text that can be shared, and spread copies the profile and adds the number of posts without changing profile itself.

Destructuring

Destructuring pulls values out into variables in one line. Arrays unpack by position; objects unpack by name.

Unpacking

const [first, second] = ["gold", "silver", "bronze"];
const { name, level = 1 } = { name: "Phoebe" };
console.log(first, second);
console.log(name, level);

Output

gold silver
Phoebe 1

Spread

... spreads an array or object out. Use it to copy or merge without changing the original. Later properties win when keys clash.

Copy and merge

const base = { sound: true, theme: "dark" };
const mine = { ...base, theme: "light" };
const a = [1, 2];
const b = [...a, 3];
console.log(mine.theme, base.theme);
console.log(b.join(","), a.length);

Output

light dark
1,2,3 2

JSON

JSON is how apps send data as text. JSON.stringify(value) turns data into a string; JSON.parse(text) turns it back. Keys and strings must use double quotes.

Round trip

const save = { user: "Ada", xp: [10, 20] };
const text = JSON.stringify(save);
console.log(text);
const back = JSON.parse(text);
console.log(back.xp[1]);

Output

{"user":"Ada","xp":[10,20]}
20

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.