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
Write a JavaScript program to find the sum and average of array elements
Write a JavaScript program to find the largest and smallest number in an array
Write a JavaScript program to remove duplicates from an array
Write a JavaScript program to filter even numbers and double them
Write a JavaScript program to count the frequency of words in a sentence
Interview Questions & Answers
What is the difference between map and forEach?
What is the difference between slice and splice?
What is the difference between shallow copy and deep copy in JavaScript?
What is the difference between spread and rest operators?
What are Map and Set in JavaScript?
How do you check if a variable is an array in JavaScript?