JavaScript: JavaScript Objects
Objects are the most essential data structure in JavaScript. Think of them as info cards — the front says "Name: Alice" and the back says "Age: 20". Each piece of information has a key and a value, forming a key-value pair.
1. Creating and Working with Objects
(1) Creating Object Literals
Use curly braces {} to write an object directly — this is the most common approach:
<!-- Script tag -->
<script>
const student = {
name: "Alice",
age: 20,
major: "Computer Science"
};
console.log(student);
</script>
Key-value pairs are separated by colons, and pairs are separated by commas. A trailing comma after the last pair is allowed (and convenient for future additions).
(2) Accessing Properties
Two ways to access object properties:
| Method | Syntax | When to Use |
|---|---|---|
| Dot notation | obj.name |
When the property name is a valid identifier |
| Bracket notation | obj["name"] |
When the name contains special characters or is stored in a variable |
Bracket notation's biggest advantage: you can use a variable as the key.
<!-- Script tag -->
<script>
const key = "name";
console.log(student[key]); // Same as student["name"]
</script>
(3) Modifying and Adding Properties
After creating an object, you can modify existing properties or add new ones at any time — even if the object was declared with const (const locks the reference, not the content).
<!-- Script tag -->
<script>
student.age = 21; // Modify
student.grade = "Junior"; // Add new property
console.log(student);
</script>
(4) Deleting Properties
Use the delete operator to remove a property entirely:
<!-- Script tag -->
<script>
delete student.grade;
console.log(student);
</script>
After deletion, accessing that property returns undefined.
(5) Methods
A function inside an object is called a method. When a function becomes a property value, the object can "do things":
<!-- Script tag -->
<script>
const dog = {
name: "Rex",
bark() {
return "Woof! I'm " + this.name;
}
};
console.log(dog.bark());
</script>
(6) The this Keyword
this refers to "the current object" — whoever calls the method, this is that object. This is one of JavaScript's trickiest concepts: if a method is extracted and called separately, this no longer points to the original object.
<!-- Script tag -->
<script>
const bark = dog.bark;
console.log(bark()); // this no longer points to dog — may be window or undefined
</script>
(7) Constructors
When you need to batch-create multiple objects with the same structure, use a constructor function:
<!-- Script tag -->
<script>
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHi = function() {
return "Hi, I'm " + this.name;
};
}
const p1 = new Person("Bob", 25);
const p2 = new Person("Charlie", 30);
console.log(p1.sayHi());
console.log(p2.sayHi());
</script>
new does three things: creates an empty object → sets this to point to it → returns the object.
(8) Object.keys / values / entries
These three static methods return arrays of an object's keys, values, and key-value pairs:
| Method | Returns |
|---|---|
Object.keys(obj) |
["name", "age"] |
Object.values(obj) |
["Alice", 20] |
Object.entries(obj) |
[["name","Alice"], ["age",20]] |
Very useful for iterating over objects: Object.keys(obj).forEach(key => ...).
▶ Example: Creating a Student Object and Displaying Info
▶ Try it Yourself▶ Example: Dot Notation vs Bracket Notation
▶ Try it Yourself▶ Example: Dynamically Adding, Modifying, and Deleting Properties
▶ Try it Yourself▶ Example: Constructors and Object.keys/values/entries
▶ Try it Yourself❓ FAQ
undefined, and so on. JSON is a text format where keys must use double quotes and values can only be strings, numbers, booleans, null, arrays, or objects. You can convert an object to a JSON string with JSON.stringify(obj) and convert it back with JSON.parse(str).const locks the variable's reference (keeping it pointing to the same object), not the object's contents. You can add, change, and delete properties, but you cannot reassign it with obj = {}."home-city"), or when the property name is stored in a variable and needs dynamic access, for example obj[key]. Otherwise dot syntax is more concise, so prefer it.📖 Summary
- Objects are created with
{}, store data as key-value pairs, accessed via dot or bracket notation - Bracket notation is for dynamic keys and special characters; dot notation is preferred for simplicity
- Object methods access properties via
this, whose value depends on the calling context - Constructors with
newcreate multiple objects with the same structure Object.keys/values/entriesiterate over keys, values, and key-value pairs
📝 Exercises
- Create a
bookobject withtitle,author, andyearproperties, plus agetSummary()method that returns a string like"title by author, published in year". - Write a constructor
Car(brand, model, year), use it to create 3 cars, then useObject.keysto list all property names of one car. - Dynamically add a
drive()method to any of the cars above (returns"brand model is driving"), then call it. Observe howthisrefers to the current object inside the method.