Object Basics

Creating Objects

Example

An object is a collection of key: value pairs (properties):

const student = {
  name: "Asha",
  age: 21,
  skills: ["HTML", "CSS"],
  address: { city: "Hyderabad", pin: "500001" },
};
console.log(student.name);              // dot notation
console.log(student["age"]);            // bracket notation
console.log(student.address.city);
console.log(student.phone);             // missing property: undefined

Output

Asha
21
Hyderabad
undefined

Adding, Changing and Deleting

Example

const car = { brand: "Tata" };
car.model = "Nexon";             // add
car.brand = "Tata Motors";       // change
const key = "year";
car[key] = 2024;                 // dynamic key
delete car.model;                // remove
console.log(car);
console.log("brand" in car, car.hasOwnProperty("model"));

Output

{ brand: 'Tata Motors', year: 2024 }
true false

Shorthand and Computed Keys

Example

const name = "Neha", role = "mentor";
const field = "level";
const user = { name, role, [field]: "senior" };
console.log(user);

Output

{ name: 'Neha', role: 'mentor', level: 'senior' }