🍰Objects

An object is a collection of key-value pairs. The keys are strings (or symbols), and the values can be any type of data (strings, numbers, functions, other objects, etc.). Objects are used to store and organize data, and can be used to represent real-world objects and their properties.

There are several ways to create an object in JavaScript:

Object Literal notation:

let person = {
  name: "John",
  age: 30,
  job: "Developer"
};

Using the Object constructor:

let person = new Object();
person.name = "John";
person.age = 30;
person.job = "Developer";

Using Object.create() method:

let personProto = {
  calculateAge: function() {
    console.log(2020 - this.yearOfBirth);
  }
};

let john = Object.create(personProto);
john.name = "John";
john.yearOfBirth = 1990;
john.job = "teacher";

You can access the properties of an object using dot notation (object.property) or bracket notation (object["property"]). For example:

console.log(person.name); // Output: "John"
console.log(person["age"]); // Output: 30

You can also add or modify properties of an object:

person.age = 35;
person.address = "New York";

Objects can also have methods, which are functions that are properties of the object. For example:

let car = {
  brand: "Toyota",
  model: "Camry",
  start: function() {
    console.log("The car is starting.");
  }
};

car.start(); // Output: "The car is starting."

Objects in JavaScript are reference types, which means that when you create an object, you're creating a reference to the memory location where the object is stored.

As objects are used to store and organize data, they are used in many places in JavaScript such as in web development with DOM, in react and vue as state and props, in nodeJS as options and callback, and many more.

Last updated