Working with Objects
Objects are collections of key-value pairs. They allow you to group related data and functions together.
Objects are one of the most important data types in JavaScript and are used everywhere.
Example
// Creating Objects
const person = {
name: 'John',
age: 30,
city: 'New York',
isStudent: false
};
// Accessing Properties
console.log(person.name); // Dot notation
console.log(person['age']); // Bracket notation
// Modifying Properties
person.age = 31;
person['city'] = 'Boston';
// Adding Properties
person.email = 'john@example.com';
// Object Methods
const calculator = {
value: 0,
add: function(num) {
this.value += num;
return this.value;
},
reset: function() {
this.value = 0;
}
};
calculator.add(10); // 10
calculator.add(5); // 15
// Object Destructuring
const { name, age } = person;
console.log(name, age); - Objects store key-value pairs
- Access with dot notation (obj.key)
- Access with bracket notation (obj['key'])
- Can contain any data type
- Methods are functions inside objects
- this keyword refers to the object
- Destructuring extracts values easily
Try Objects
HTML
<div class="object-demo">
<h3>Create Your Profile</h3>
<input type="text" id="userName" placeholder="Name">
<input type="number" id="userAge" placeholder="Age">
<input type="text" id="userCity" placeholder="City">
<button onclick="createProfile()">Create Profile</button>
<div id="profileOutput"></div>
</div> CSS
.object-demo { padding: 20px; background: #f0f0f0; border-radius: 8px; }
input { padding: 10px; margin: 5px; border: 1px solid #ddd; border-radius: 4px; display: block; width: 250px; }
button { padding: 10px 20px; background: #d1039e; color: white; border: none; border-radius: 5px; cursor: pointer; margin: 10px 0; }
#profileOutput { margin-top: 15px; padding: 15px; background: white; border-radius: 5px; border-left: 4px solid #d1039e; } JavaScript
function createProfile() {
const profile = {
name: document.getElementById('userName').value || 'Guest',
age: document.getElementById('userAge').value || 0,
city: document.getElementById('userCity').value || 'Unknown',
introduce: function() {
return `Hi! I'm ${this.name}, ${this.age} years old, from ${this.city}.`;
},
birthday: function() {
this.age++;
return `Happy Birthday! You are now ${this.age} years old.`;
}
};
let output = `
<strong>Profile Created:</strong><br>
${profile.introduce()}<br><br>
<button onclick="alert('${profile.birthday()}')">Celebrate Birthday ๐</button>
`;
document.getElementById('profileOutput').innerHTML = output;
} Notes
- Objects are fundamental to JavaScript. Almost everything in JavaScript is an object!
