JavaScript Objects

Introduction to Objects

Objects in JavaScript are collections of key-value pairs. They allow you to group related data and functions together. Here's an example of creating and using an object:

const car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2020,
  start: function() {
    console.log("The car has started.");
  }
};

// Accessing properties
console.log(car.brand); // "Toyota"

// Calling methods
car.start(); // "The car has started."

Properties & Methods

Learn how to define and access properties and methods on objects.

Prototypes

Every JavaScript object has a prototype, which is another object from which it inherits properties and methods. This is the basis of JavaScript's prototype chain. Here's an example:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  console.log("Hello, my name is " + this.name);
};

const john = new Person("John", 30);
john.greet(); // "Hello, my name is John"