What is an Object?
An object is a collection of key-value pairs. Unlike arrays which are ordered lists, objects are unordered collections that you access by name (the key).
💡 Real-world analogy
Think of an object like a real-world object — a person has a name, age, and can walk. In JavaScript, an object can have properties (name, age) and methods (walk).
Creating Objects
// Object literal (preferred)
let person = {
name: "Alice",
age: 25,
city: "New York"
};
// Using the Object constructor
let car = new Object();
car.make = "Toyota";
car.model = "Camry";
Accessing Properties
Two ways: dot notation or bracket notation.
let person = { name: "Alice", age: 25 };
// Dot notation
console.log(person.name); // "Alice"
// Bracket notation (useful for dynamic keys)
console.log(person["age"]); // 25
// Adding new properties
person.city = "New York";
Object Methods
A method is a function that belongs to an object.
let person = {
name: "Alice",
age: 25,
greet: function() {
console.log("Hello, I'm " + this.name);
}
};
person.greet(); // "Hello, I'm Alice"
The this Keyword
this refers to the object that the method belongs to. It's one of the most important concepts in JavaScript.
let person = {
name: "Alice",
introduce: function() {
return "My name is " + this.name;
}
};
console.log(person.introduce()); // "My name is Alice"
Common Mistakes
- Confusing
thisbehavior in different contexts (we'll cover this in detail later) - Forgetting to use
newwhen using constructor functions - Accidentally creating global variables when using objects
Quick Quiz
1. How do you access the name property of an object person?
2. What does this refer to in an object method?
3. What is a method in an object?
Summary
- Objects are collections of key-value pairs
- Use dot notation or bracket notation to access properties
- Methods are functions stored as properties
thisrefers to the object the method belongs to- Use
Object.keys()andObject.values()to iterate
