In JavaScript, an object is a collection of key-value pairs. Think of an object as a real-world object: it has properties (attributes) and methods (actions it can perform). Objects allow you to store complex data and organize it logically.
1️⃣ Creating an Object
You can create an object using curly braces {}:
let person = {
name: "Alice",
age: 25,
city: "Paris"
};
console.log(person);
name, age, city → properties (keys)"Alice", 25, "Paris" → values2️⃣ Accessing Object Properties
You can access values using either dot notation or bracket notation:
// Dot notation console.log(person.name); // Alice // Bracket notation console.log(person["age"]); // 25
let key = "city"; console.log(person[key]); // Paris
3️⃣ Modifying Object Properties
You can update, add, or delete properties:
// Update existing property
person.age = 26;
// Add new property
person.country = "France";
// Delete property
delete person.city;
console.log(person);
// { name: "Alice", age: 26, country: "France" }
4️⃣ Objects with Methods
Objects can have functions as properties, called methods:
let person = {
name: "Alice",
age: 25,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet(); // Hello, my name is Alice
this refers to the current object5️⃣ Looping Through Object Properties
You can use a for...in loop to iterate over keys:
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// name: Alice
// age: 25
// greet: function() { ... }
Explanation:
person object stores properties and a methodfor...in loop displays all keys and values dynamically<!DOCTYPE html>
<html>
<head>
<title>JavaScript Objects Example</title>
<style>
body { font-family: Arial; padding: 20px; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
p { font-size: 18px; color: darkblue; }
</style>
</head>
<body>
<h1>JavaScript Objects Demo</h1>
<p id="demo">Click buttons to see object operations</p>
<button onclick="showPerson()">Show Person Info</button>
<button onclick="updateAge()">Update Age</button>
<button onclick="addCountry()">Add Country</button>
<button onclick="callGreet()">Call Greet Method</button>
<script>
let person = {
name: "Alice",
age: 25,
city: "Paris",
greet: function() {
return "Hello, my name is " + this.name;
}
};
function showPerson() {
let message = "";
for (let key in person) {
message += key + ": " + person[key] + "<br>";
}
document.getElementById("demo").innerHTML = message;
}
function updateAge() {
person.age = 26;
document.getElementById("demo").innerHTML = "Age updated to: " + person.age;
}
function addCountry() {
person.country = "France";
document.getElementById("demo").innerHTML = "Country added: " + person.country;
}
function callGreet() {
document.getElementById("demo").innerHTML = person.greet();
}
</script>
</body>
</html>