Object

An object is a collection of key-value pairs that stores related data and functionality together. Objects are fundamental to JavaScript and used to represent complex data structures.

Creating Objects

javascript
// Object literal
const person = {
  name: 'Alice',
  age: 30,
  greet() {
    console.log(`Hi, I'm ${this.name}`)
  }
}

// Constructor
const car = new Object()
car.brand = 'Toyota'
car.year = 2024

// Object.create()
const animal = Object.create(null)

Accessing Properties

javascript
// Dot notation
console.log(person.name)

// Bracket notation
console.log(person['age'])

// Useful for dynamic keys
const key = 'name'
console.log(person[key])

Object Methods

javascript
// Get keys
Object.keys(person) // ['name', 'age', 'greet']

// Get values
Object.values(person) // ['Alice', 30, [Function]]

// Get entries
Object.entries(person) // [['name', 'Alice'], ...]

// Merge objects
const merged = Object.assign({}, obj1, obj2)
const spread = { ...obj1, ...obj2 }

Destructuring

javascript
const { name, age } = person
console.log(name) // 'Alice'

// With rename
const { name: personName } = person

// With defaults
const { city = 'Unknown' } = person

Object-Oriented Features

javascript
// Methods
const calculator = {
  add(a, b) {
    return a + b
  },
  subtract(a, b) {
    return a - b
  }
}

// this keyword
const user = {
  name: 'Bob',
  getName() {
    return this.name
  }
}

Learn More