In JavaScript, almost everything is an object. An object is a collection of key-value pairs, where keys are strings (or symbols) and values can be any data type, including other objects or functions.

Object Literals

The simplest way to create an object is using the object literal syntax ({}).

JavaScript


const user = {
  // Properties (key: value)
  firstName: "Jane",
  lastName: "Doe",
  age: 28,
  isOnline: true,
  
  // Method (a function as a property)
  greet: function() {
    // 'this' refers to the object the method is called on
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
  }
};

// Accessing properties with dot notation
console.log(user.firstName); // "Jane"

// Accessing properties with bracket notation (useful for dynamic keys)
console.log(user['isOnline']); // true

// Calling a method
user.greet(); // "Hello, my name is Jane Doe."

Prototypal Inheritance

JavaScript doesn't have "classes" in the same way languages like Java or C++ do. Instead, it uses prototypal inheritance.

Every JavaScript object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on, until an object is reached with null as its prototype. This is called the prototype chain.

When you try to access a property on an object, JavaScript first looks at the object itself. If it doesn't find it, it looks at the object's prototype. If it's not there, it looks at the prototype's prototype, and so on up the chain.

Code Snippet: The Prototype Chain in Action

Let's create a dog object and an object myPet that inherits from dog.

JavaScript


// A parent object (the prototype)
const dog = {
  makesSound: function() {
    console.log("Woof!");
  }
};

// Create a new object that inherits from 'dog'
const myPet = Object.create(dog);
myPet.name = "Buddy"; // Add a property to the new object

// We can call makesSound() on myPet, even though it's not defined directly on it.
// JavaScript finds it by walking up the prototype chain to 'dog'.
myPet.makesSound(); // "Woof!"

console.log(myPet.name); // "Buddy"

// hasOwnProperty checks if the property exists directly on the object
console.log(myPet.hasOwnProperty('name'));       // true
console.log(myPet.hasOwnProperty('makesSound')); // false (it's on the prototype)

The class Syntax (Syntactic Sugar)

Modern JavaScript (ES6+) introduced the class keyword. It's important to understand that this is primarily syntactic sugar over the existing prototypal inheritance model. It provides a cleaner, more familiar syntax for creating objects and handling inheritance, but under the hood, it's still using prototypes.

JavaScript


class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Cat extends Animal {
  speak() {
    console.log(`${this.name} meows.`);
  }
}

const myCat = new Cat('Milo');
myCat.speak(); // "Milo meows."