Objects

An object is a collection of key-value pairs.

let person = {
    name: "John",
    age: 25,
    city: "London"
};

console.log(person);

Output:

{
   name: "John",
   age: 25,
   city: "London"
}

Why Objects?

Without objects:

let name = "John";
let age = 25;
let city = "London";

With objects:

let person = {
   name: "John",
   age: 25,
   city: "London"
};

Everything related stays together.


Accessing Properties

Dot Notation

console.log(person.name);
console.log(person.age);

Output:

John
25

Bracket Notation

console.log(person["name"]);

Output:

John

Useful when property name is dynamic.

let key = "age";

console.log(person[key]);

Output:

25

Updating Properties

person.age = 30;

console.log(person);

Output:

{
   name: "John",
   age: 30,
   city: "London"
}

Adding Properties

person.country = "UK";

Output:

{
   name: "John",
   age: 30,
   city: "London",
   country: "UK"
}

Deleting Properties

delete person.city;

Output:

{
   name: "John",
   age: 30,
   country: "UK"
}

Nested Objects

Objects can contain objects.

let user = {
   name: "John",
   address: {
      city: "London",
      zip: 12345
   }
};

console.log(user.address.city);

Output:

London

Object Methods

Methods are functions inside objects.

let person = {
   name: "John",

   greet: function() {
      console.log("Hello");
   }
};

person.greet();

Output:

Hello

Real Example

let calculator = {
   add(a,b){
      return a+b;
   },

   sub(a,b){
      return a-b;
   }
};

console.log(calculator.add(5,3));

Output:

8