Back to journal
·2 min readJavaScriptObjectsOopPrototypesInheritance

JavaScript Objects: Your Quick Guide

Objects in JS are just key-value bags you can grow and change. Here's creation, access, methods, iteration, and prototypes without the textbook voice.

ShareCopy failed

Objects are how JavaScript models almost everything. Keys are strings or symbols. Values can be nested objects, functions, whatever you need.

Creating objects

Literals are what you'll reach for most days:

const person = {
  firstName: "Pantelis",
  lastName: "Theodosiou",
  age: 28,
  address: {
    street: "123 Main St",
    city: "Thessaloniki",
    country: "Greece",
  },
};

You can also use new Object(), constructor functions, or class. Literals win on readability for plain data.

Reading and writing properties

Dot notation is fine when the key is a valid identifier:

console.log(person.firstName); // Pantelis

Bracket notation when the key is dynamic or weird:

console.log(person["lastName"]); // Theodosiou

Update with assignment:

person.age = 31;
console.log(person.age); // 31

Objects are mutable. You can add keys after creation.

Methods

Functions on objects are just properties whose value is callable:

const car = {
  brand: "Nissan",
  model: "Skyline R34",
  start: function () {
    console.log("The beast started");
  },
  stop: function () {
    console.log("The beast stopped");
  },
};

car.start();
car.stop();

Iteration

for...in still shows up in older codebases:

for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

Object.keys(), Object.values(), and Object.entries() give you arrays you can map over.

Prototypes

JavaScript inherits through the prototype chain, not classical classes (even when you write class).

const animal = {
  greeting: function () {
    console.log("Animal says hi!");
  },
};

const dog = Object.create(animal);

dog.bark = function () {
  console.log("Woof! Woof!");
};

dog.greeting();
dog.bark();

dog doesn't own greeting, but it finds it on animal.

If you're modeling data in JS, get comfortable with objects early. Everything else (arrays, functions, modules) sits on top of this shape.

ShareCopy failed