JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Objects

5 April 2025 | Category:

📌 What is an Object in JavaScript?

In JavaScript, an object is a collection of key-value pairs.
Think of it like a real-world item — for example, a car has properties like color, model, and speed.
In code, we store such related data in objects.


🛠️ 1. Creating an Object

const person = {
  name: "Alice",
  age: 25,
  isStudent: false
};
  • name, age, and isStudent are keys (or properties)
  • "Alice", 25, and false are values

🔎 2. Accessing Object Properties

➤ Dot Notation:

console.log(person.name); // Alice

➤ Bracket Notation:

console.log(person["age"]); // 25

Use bracket notation if the key has spaces or is stored in a variable.


✏️ 3. Modifying Object Properties

person.age = 26;             // Change value
person["isStudent"] = true;  // Change using brackets

➕ 4. Adding New Properties

person.city = "Delhi";

❌ 5. Deleting Properties

delete person.isStudent;

🔁 6. Looping Through Object Properties

for (let key in person) {
  console.log(key + ":", person[key]);
}

🧠 7. Nested Objects

const user = {
  name: "John",
  address: {
    city: "Mumbai",
    zip: 400001
  }
};

console.log(user.address.city); // Mumbai

📦 8. Object Methods (Function inside an Object)

const user = {
  name: "Ravi",
  greet: function() {
    console.log("Hello, " + this.name);
  }
};

user.greet(); // Hello, Ravi
  • this refers to the object itself.

📋 9. Object.keys(), Object.values(), Object.entries()

const product = { name: "Phone", price: 500 };

console.log(Object.keys(product));   // ["name", "price"]
console.log(Object.values(product)); // ["Phone", 500]
console.log(Object.entries(product));// [["name", "Phone"], ["price", 500]]

🧬 10. Spread Operator with Objects

const obj1 = { a: 1 };
const obj2 = { b: 2 };

const combined = { ...obj1, ...obj2 };
console.log(combined); // { a: 1, b: 2 }

🚀 11. Object Destructuring

const car = {
  brand: "BMW",
  color: "Black"
};

const { brand, color } = car;
console.log(brand); // BMW
console.log(color); // Black

📌 Summary

OperationExample
Create objectconst obj = { key: value }
Access propertyobj.key or obj["key"]
Modify propertyobj.key = newValue
Add propertyobj.newKey = value
Delete propertydelete obj.key
Loop through objectfor (let key in obj)
Get keys/valuesObject.keys(obj)
Destructure objectconst { a, b } = obj