Objects

Working with JavaScript objects, methods, and modern object syntax

#objects #properties #methods #destructuring

Objects

JavaScript objects are collections of key-value pairs.

Object Creation

// Object literal
const person = {
  name: "Alice",
  age: 30,
  greet() {
    return `Hello, I'm ${this.name}`;
  }
};

console.log(person.greet());  // Hello, I'm Alice

Property Access

const user = {
  name: "Bob",
  email: "bob@example.com",
  "favorite-color": "blue"
};

// Dot notation
console.log(user.name);  // Bob

// Bracket notation
console.log(user["email"]);  // bob@example.com
console.log(user["favorite-color"]);  // blue

Object Methods

const obj = {
  a: 1,
  b: 2,
  c: 3
};

// Get keys
const keys = Object.keys(obj);
console.log(keys);  // ['a', 'b', 'c']

// Get values
const values = Object.values(obj);
console.log(values);  // [1, 2, 3]

// Get entries
const entries = Object.entries(obj);
console.log(entries);  // [['a', 1], ['b', 2], ['c', 3]]

Object Spread and Merge

const defaults = { theme: "dark", lang: "en" };
const userPrefs = { lang: "fr", fontSize: 14 };

// Merge objects (later properties override)
const config = { ...defaults, ...userPrefs };
console.log(config);
// { theme: 'dark', lang: 'fr', fontSize: 14 }

Computed Property Names

const key = "dynamicKey";
const value = "dynamicValue";

const obj = {
  [key]: value,
  [`${key}2`]: "another value"
};

console.log(obj.dynamicKey);  // dynamicValue
console.log(obj.dynamicKey2);  // another value

Object Destructuring with Defaults

const settings = { volume: 50 };

const {
  volume = 100,
  brightness = 80
} = settings;

console.log(volume);  // 50
console.log(brightness);  // 80 (default)

Nested Object Access

const data = {
  user: {
    profile: {
      name: "Charlie",
      age: 25
    }
  }
};

// Optional chaining
console.log(data?.user?.profile?.name);  // Charlie
console.log(data?.user?.address?.city);  // undefined (no error)

Object.assign()

const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };

Object.assign(target, source1, source2);
console.log(target);  // { a: 1, b: 2, c: 3 }

Object Freezing and Sealing

const obj = { name: "Diana" };

// Freeze (no modifications)
Object.freeze(obj);
obj.name = "Eve";  // Fails silently
console.log(obj.name);  // Diana

// Seal (can modify, can't add/delete)
const sealed = { count: 0 };
Object.seal(sealed);
sealed.count = 10;  // Works
sealed.newProp = 5;  // Fails
console.log(sealed);  // { count: 10 }

Discover another handy tool from EditPDF.pro