# Objects and JSON
# Objects and arrays
Objects group named values; arrays represent ordered collections:
const student = {
name: 'Ada',
scores: [98, 100],
summary() {
return `${this.name}: ${this.scores.length} scores`;
}
};
student.name;
student['scores'];
student.summary();
Use destructuring for the values you need:
const { name, scores } = student;
const [firstScore, secondScore] = scores;
Optional chaining avoids an error when an intermediate value is missing:
const city = student.address?.city ?? 'Unknown city';
Objects and arrays are references. Mutating a reference changes the same object; spreading creates a shallow copy:
const updated = { ...student, name: 'Grace' };
const copiedScores = [...student.scores];
# JSON is text
JSON is a language-independent text format commonly used in HTTP bodies. A JavaScript object and its JSON representation are different values:
const data = { name: 'Ada', active: true };
const text = JSON.stringify(data);
const restored = JSON.parse(text);
JSON supports strings, finite numbers, booleans, null, arrays, and objects. Functions and undefined are not represented as JSON values; dates and other special objects need an explicit representation such as a string.
Continue with Async HTTP for requests and DOM and events for rendering data.