NelsonLabs

Objects

Objects group related data together under named properties. Almost everything in JavaScript is an object — they're the primary way to model real-world things in code.

Objects — creation and access
javascript
// Object literal — the most common way
const user = {
  name:       "Nelson Njihia",
  age:        26,
  role:       "engineer",
  isActive:   true,
  courses:    ["JavaScript", "Python"],  // array as property
};

// Dot notation — preferred
user.name      // "Nelson Njihia"
user.courses   // ["JavaScript", "Python"]

// Bracket notation — needed for dynamic keys or special characters
user["name"]   // "Nelson Njihia"
const key = "role";
user[key]      // "engineer"

// Adding and updating properties
user.email   = "nelson@nelsonlabs.dev";  // add
user.age     = 27;                       // update

// Deleting properties
delete user.isActive;
Methods — functions inside objects
javascript
const course = {
  title: "JavaScript Basics",
  chapters: 14,
  isLive: true,

  // Method — a function stored as a property
  describe() {
    return `${this.title}: ${this.chapters} chapters`;
    // 'this' refers to the object the method belongs to
  },

  toggleLive() {
    this.isLive = !this.isLive;
  },
};

course.describe();  // "JavaScript Basics: 14 chapters"
Destructuring and spread
javascript
const user = { name: "Nelson", age: 26, city: "Nairobi" };

// Destructuring — extract properties into variables
const { name, age }          = user;
const { name: userName, city } = user;  // rename on extraction
const { name, ...rest }       = user;   // rest = { age: 26, city: "Nairobi" }

// Spread — copy and extend objects
const updatedUser = { ...user, age: 27, email: "n@nelsonlabs.dev" };
// { name: "Nelson", age: 27, city: "Nairobi", email: "..." }

// Common pattern: updating state in React
const newState = { ...currentState, loading: false, data: response };