What is an Object in JavaScript?
In JavaScript, an object is a collection of key-value pairs. Each key is called a property, and if the value is a function, it's called a method.
Creating an Object
You can create an object using curly braces {}
and define properties inside it.
const person = {
name: "Alice",
age: 25,
isStudent: true
};
console.log(person);
Output:
{ name: 'Alice', age: 25, isStudent: true }
Accessing Object Properties
There are two ways to access properties: dot notation and bracket notation.
console.log(person.name); // Dot notation
console.log(person["age"]); // Bracket notation
Output:
Alice 25
Adding and Updating Properties
You can add or update properties at any time using assignment.
person.city = "New York"; // Adding
person.age = 26; // Updating
console.log(person);
Output:
{ name: 'Alice', age: 26, isStudent: true, city: 'New York' }
Deleting Properties
You can remove a property using the delete
keyword.
delete person.isStudent;
console.log(person);
Output:
{ name: 'Alice', age: 26, city: 'New York' }
What is a Method in JavaScript?
A method is a function inside an object. It defines behavior related to that object.
Defining Methods
const user = {
name: "Bob",
greet: function() {
return "Hello, " + this.name + "!";
}
};
console.log(user.greet());
Output:
Hello, Bob!
Why use this
?
The this
keyword refers to the current object. Inside a method, this
lets you access other properties of the same object.
ES6 Shorthand for Methods
From ES6 onwards, you can define methods in a shorter way:
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3));
console.log(calculator.subtract(10, 4));
Output:
8 6
Can an object hold both data and behavior?
Yes! This is the core of Object-Oriented Programming (OOP). Objects group related data (properties) and behavior (methods).
Example: Complete Object with Multiple Methods
const car = {
brand: "Toyota",
model: "Camry",
year: 2020,
getDetails() {
return this.brand + " " + this.model + " (" + this.year + ")";
},
isNew() {
return this.year >= 2022;
}
};
console.log(car.getDetails());
console.log("Is new car:", car.isNew());
Output:
Toyota Camry (2020) Is new car: false
Questions You Might Ask
Q: Can we store arrays and other objects as property values?
A: Yes! JavaScript objects can hold any data type, including arrays, functions, and other objects.
const student = {
name: "John",
subjects: ["Math", "Science"],
address: {
city: "Delhi",
zip: 110001
}
};
console.log(student.subjects[0]); // Math
console.log(student.address.city); // Delhi
Output:
Math Delhi
Summary
- Objects group related data and functions.
- Properties are key-value pairs inside an object.
- Methods are functions defined as values of properties.
- this refers to the current object inside a method.