Chapter 4 Cheatsheet: Objects
This cheatsheet summarizes the mechanics of plain JavaScript objects covered in Chapter 4. Use it as a quick reference when dealing with complex data structures.
Creating and Modifying Objects
Objects store data in key-value pairs. They are highly mutable, even when declared with const.
const user = {
name: "John",
age: 30
};
// Add new properties dynamically
user.isActive = true;
// Access using Bracket Notation (for dynamic keys)
const key = "name";
console.log(user[key]); // "John"
Shorthand Syntaxes
No Colon Syntax If the variable name matches the key you want to create, omit the colon.
const radius = 5;
const circle = { radius }; // Evaluates to { radius: 5 }
Spread Syntax (...)
Shallow-copy or merge objects together. Conflicts are resolved by the right-most object.
const merged = { ...defaultConfig, ...userConfig };
Safe Navigation
Optional Chaining (?.)
Prevents runtime crashes when trying to access properties on an object that might be null or undefined. Only use it when the data is legitimately optional.
// Safely returns undefined if 'address' doesn't exist
const zip = user.address?.zipCode;
Initializing Missing Properties
Use the ! operator to safely initialize numeric or string properties before modifying them.
if (!scores.player1) scores.player1 = 0;
Functions and Objects
Returning Objects Because JavaScript functions can only return a single value, package multiple returns into an object.
Destructuring Unpack object properties into standalone variables instantly.
const { sum, difference } = doAllTheMath(10, 5);
Methods and this
- Standard methods use
thisto refer to the object they belong to. - Arrow Functions do not have a
thiscontext; they inherit it from their parent scope. Avoid using them for object methods. - Methods lose their
thiscontext if passed as standalone callbacks. Use.bind(obj)to lock the context.