JavaScript Objects

An object stores related data as key: value pairs. The keys are called properties.

const user = {
  name: "Robin",
  age: 25,
  city: "Delhi"
};

console.log(user.name);
console.log(user["age"]);
Output of the above program is

Robin
25


Change, add and delete properties

const car = { brand: "Tata", year: 2020 };

car.year = 2024;          // change
car.color = "blue";       // add
delete car.brand;         // delete
console.log(car);
Output of the above program is

{ year: 2024, color: "blue" }

Even if the object is a const, you can change its properties.


Methods

A function stored in an object is called a method. Inside it, this means the object.

const person = {
  firstName: "Robin",
  lastName: "Kumar",
  fullName() {
    return this.firstName + " " + this.lastName;
  }
};

console.log(person.fullName());
Output of the above program is

Robin Kumar


Nested objects and optional chaining

const student = {
  name: "Asha",
  address: { city: "Jaipur" }
};

console.log(student.address.city);
console.log(student.contact?.phone);
Output of the above program is

Jaipur
undefined

?. (optional chaining) stops and gives undefined when a part is missing, instead of an error.


Object.keys, values and entries

const product = { name: "Pen", price: 10 };

console.log(Object.keys(product));
console.log(Object.values(product));
console.log(Object.entries(product));
console.log("price" in product);
Output of the above program is

[ "name", "price" ]
[ "Pen", 10 ]
[ [ "name", "Pen" ], [ "price", 10 ] ]
true


Copy an object

const a = { x: 1, y: 2 };
const b = { ...a, y: 20 };   // copy and change y
console.log(b);
Output of the above program is

{ x: 1, y: 20 }

Note: Objects are copied by reference. const b = a does not make a copy; both names point to the same object. Use { ...a } for a copy.

Summary

  • Objects store key: value pairs.
  • Read with obj.key or obj["key"].
  • Functions inside objects are methods and use this.
  • Next: Constructor Functions.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.