An object groups related data as key: value pairs.
const student = {
name: 'Asha',
age: 20,
course: 'BCA',
greet() {
return 'Hi, I am ' + this.name;
}
};
Read values
- Dot notation:
student.name - Bracket notation:
student['course'](useful when the key is in a variable)
Change, add, delete
student.age = 21;student.city = 'Gaya';delete student.course;
Methods and this
A function inside an object is a method. Inside it, this refers to the object.
Useful helpers
Object.keys(obj), Object.values(obj), Object.entries(obj) return arrays you can loop over.
Example
Example — Student object
HTML
<pre id="out"></pre>
<script>
const student = {
name: 'Asha',
marks: { html: 88, css: 92, js: 79 },
average() {
const list = Object.values(this.marks);
return list.reduce((a, b) => a + b, 0) / list.length;
}
};
student.city = 'Gaya';
let text = `${student.name} from ${student.city}\n`;
for (const [subject, mark] of Object.entries(student.marks)) {
text += `${subject.toUpperCase()}: ${mark}\n`;
}
text += 'Average: ' + student.average().toFixed(1);
document.getElementById('out').textContent = text;
</script>