Objects · Lesson 26 of 45
JSON and optional chaining
How data travels as text, and reading data that might be missing.
8 minutes3 games
JSON is a way to write data as text, and the language websites and servers speak. It looks like an object except: keys must be in "...", and there are no functions or undefined.
JSON.stringify(obj)turns an object into text.JSON.parse(text)turns the text back into an object.
a JavaScript object
JSON.stringify → text
sent to a server or saved
JSON.parse → object
JavaScript
const order = { id: 7, items: ["pen", "mug"], paid: true }
const text = JSON.stringify(order)
console.log(text)
console.log(typeof text)
const back = JSON.parse(text)
console.log(back.items[1])
console.log(JSON.stringify(order, null, 2))Optional chaining ?.
When data might be missing (say from an API), user.address.city throws if address doesn't exist. ?. stops and returns undefined instead of an error.
JavaScript
const user = { name: "Ali" }
console.log(user.address?.city) // undefined, no error
console.log(user.address?.city ?? "Unknown") // Unknown
console.log(user.greet?.()) // call only if it exists
console.log(user.tags?.[0])What's the output?
const data = JSON.parse('{"n": 5}')
console.log(data.n + 1)What will this code print?
Spot the bug
One line throws if there's no profile. Which?
Exercise
Parse the text and print the city (Luxor).
Expected output: Luxor
JavaScript
const text = '{"name":"Adam","address":{"city":"Luxor"}}'
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.