Codectionary / Developer documentation / JavaScript

Objects: Basics

Objects store collections of related data as key-value pairs, where keys are strings (or Symbols) and values can be any type, including functions (called methods). Properties can be accessed with dot notation or bracket notation, and objects can be created with object literals, the Object() constructor, or classes.

Syntax

const obj = { key: value, method() { } };

Examples

Creating and Accessing Objects

Basic object creation and property access.

const person = {
  name: "Alice",
  age: 25,
  greet() {
    console.log(`Hi, I am ${this.name}`);
  }
};

console.log(person.name);     // dot notation - "Alice"
console.log(person["age"]);   // bracket notation - 25
person.greet();               // "Hi, I am Alice"

Modifying and Deleting Properties

Adding, updating, and removing object properties.

const car = { make: "Toyota", model: "Corolla" };

car.year = 2024;          // adding a new property
car.model = "Camry";      // updating an existing property
delete car.make;          // removing a property

console.log(car); // { model: "Camry", year: 2024 }

Bracket Notation for Dynamic Keys

Using bracket notation when the property name is stored in a variable.

const user = { name: "Bob", email: "bob@example.com" };
const field = "email";

console.log(user[field]); // "bob@example.com"
// user.field would look for a literal property named "field" - wrong!

Best practices

  • Use dot notation when the property name is a fixed, known identifier; use bracket notation when it is dynamic or stored in a variable
  • Prefer object shorthand syntax ({ name, age } instead of { name: name, age: age }) when variable names match property names
  • Use methods shorthand (greet() { } instead of greet: function() { }) for cleaner object method definitions
  • Be careful with delete - it is relatively slow and often better replaced by restructuring data or using Map for frequently changing key sets

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation