stackademic

The leading education platform for anyone with an interest in software development.

JavaScript Objects

Store keyed properties, methods, and nested data structures

Overview

Objects group related data as key-value pairs. Keys are strings or symbols; values can be any type. Objects are reference types—assigning copies the reference, not a deep clone.

Syntax / Usage

const user = {
  name: 'Ada',
  role: 'engineer',
  active: true,
  greet() {
    return `Hi, I'm ${this.name}`
  },
}

// Access
user.email = 'ada@example.com'
user['role']  // bracket notation for dynamic keys

// Destructuring
const { name, role } = user

// Spread (shallow copy)
const clone = { ...user, role: 'lead' }

// Optional chaining
user.address?.city  // undefined if no address

// Object keys
Object.keys(user)
Object.values(user)
Object.entries(user)

Examples

Merge defaults with user options:

const defaults = { theme: 'light', lang: 'en' }
const options = { lang: 'es' }
const config = { ...defaults, ...options }
// { theme: 'light', lang: 'es' }

Index records by id:

const posts = [{ id: 'a', title: 'One' }, { id: 'b', title: 'Two' }]
const byId = Object.fromEntries(posts.map((p) => [p.id, p]))
byId.b.title  // 'Two'

Common Mistakes

  • Mutating nested objects when you meant to copy—spread is shallow only
  • Using objects as Map keys without realizing reference equality applies
  • Adding properties in loops without hasOwnProperty checks when iterating
  • Prototype pollution from unsafe Object.assign with user input

See Also

arrays destructuring spread-rest functions