Understand JavaScript objects — creating, accessing, and modifying key-value pairs, and using methods.
An object is a collection of key-value pairs. While arrays store ordered lists of values accessed by index, objects store named values accessed by key. Objects are one of the most important data structures in JavaScript — almost everything in the language is built on them.
The most common way to create an object is with an object literal — curly braces containing comma-separated properties:
const person = {
name: 'Alice',
age: 30,
city: 'Paris',
};Each property has a key (also called a name) and a value. Keys are strings (or Symbols), and values can be anything — numbers, strings, booleans, arrays, other objects, or even functions.
When a variable name matches the key name, you can use shorthand property names:
const name = 'Bob';
const age = 25;
const person = { name, age };
// Same as: { name: 'Bob', age: 25 }You can use computed property names when the key is dynamic:
const field = 'email';
const user = {
[field]: 'bob@example.com',
};
console.log(user.email); // 'bob@example.com'Nested objects are objects within objects, useful for representing structured data:
const student = {
name: 'Charlie',
grades: {
math: 92,
english: 88,
science: 95,
},
};
console.log(student.grades.math); // 92There are two ways to access properties on an object:
1. Dot notation — the most common and readable way:
const person = { name: 'Alice', age: 30 };
console.log(person.name); // 'Alice'
console.log(person.age); // 302. Bracket notation — uses a string (or expression) inside square brackets:
console.log(person['name']); // 'Alice'
console.log(person['age']); // 30Bracket notation is required in these situations:
Dynamic keys — when the property name is stored in a variable:
const key = 'name';
console.log(person[key]); // 'Alice'Keys with spaces or special characters:
const data = { 'first name': 'Alice', 'last-name': 'Smith' };
console.log(data['first name']); // 'Alice'
// data.first name — would cause a syntax error!Keys that are numbers:
const scores = { 1: 'gold', 2: 'silver', 3: 'bronze' };
console.log(scores[1]); // 'gold'Accessing a property that does not exist returns undefined:
console.log(person.email); // undefinedOptional chaining (?.) is a safe way to access nested properties without risking an error if an intermediate property is undefined or null:
const user = { profile: { bio: 'Developer' } };
console.log(user.profile?.bio); // 'Developer'
console.log(user.settings?.theme); // undefined (no error)Without ?., accessing user.settings.theme would throw a TypeError because user.settings is undefined.
Objects are mutable — you can add, update, and remove properties after creation.
Adding properties:
const person = { name: 'Alice' };
person.age = 30; // dot notation
person['email'] = 'a@b.c'; // bracket notationUpdating properties:
person.name = 'Bob'; // overwrite existing valueRemoving properties with the delete operator:
delete person.email;
console.log(person.email); // undefinedJavaScript provides useful static methods on the Object class for working with properties:
Object.keys(obj) — returns an array of all property names:
Object.keys(person); // ['name', 'age']Object.values(obj) — returns an array of all values:
Object.values(person); // ['Bob', 30]Object.entries(obj) — returns an array of [key, value] pairs:
Object.entries(person); // [['name', 'Bob'], ['age', 30]]Checking if a property exists:
The in operator checks for a property in the object and its prototype chain:
'name' in person; // true
'email' in person; // falsehasOwnProperty() checks only the object itself (not the prototype):
person.hasOwnProperty('name'); // trueThese tools make it easy to inspect and iterate over objects dynamically.
When a function is stored as a property of an object, it is called a method:
const calculator = {
result: 0,
add: function(n) {
this.result += n;
},
reset: function() {
this.result = 0;
},
};
calculator.add(5);
calculator.add(3);
console.log(calculator.result); // 8The this keyword inside a method refers to the object the method is called on. In the example above, this.result refers to calculator.result.
ES6 introduced a method shorthand syntax that is cleaner and more commonly used:
const calculator = {
result: 0,
add(n) {
this.result += n;
},
reset() {
this.result = 0;
},
};This is exactly the same as the longer add: function(n) { ... } syntax but more concise.
Methods can also return values, just like regular functions:
const person = {
firstName: 'Alice',
lastName: 'Smith',
fullName() {
return this.firstName + ' ' + this.lastName;
},
};
console.log(person.fullName()); // 'Alice Smith'Understanding this can be tricky — its value depends on how the function is called, not where it is defined. For now, just remember that inside an object method called with dot notation (person.fullName()), this refers to the object before the dot (person).
<div id="card"></div>
<script>
const person = {
name: 'Alice',
role: 'Developer',
skills: ['JavaScript', 'HTML', 'CSS'],
introduce() {
return "Hi, I'm " + this.name + ", a " + this.role + ".";
},
listSkills() {
return 'Skills: ' + this.skills.join(', ');
},
};
const card = document.getElementById('card');
const heading = document.createElement('h2');
heading.textContent = person.introduce();
card.appendChild(heading);
const para = document.createElement('p');
para.textContent = person.listSkills();
card.appendChild(para);
// Iterate over properties
const details = document.createElement('ul');
for (const [key, value] of Object.entries(person)) {
if (typeof value !== 'function') {
const li = document.createElement('li');
li.textContent = key + ': ' + value;
details.appendChild(li);
}
}
card.appendChild(details);
</script>How do you access a property called 'first name' (with a space) on an object?