JavaScript Object Methods
5 April 2025 | Category: JavaScript
Absolutely! Let’s break down JavaScript Object Methods step-by-step in a beginner-friendly way, with examples, real use cases, and everything you need to understand this concept like a pro. đ„
đ§ What is a Method in JavaScript?
A method is simply a function inside an object.
It lets an object do something â like greet a user, calculate age, or return full name.
đ ïž 1. Creating an Object Method
const person = {
firstName: "John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // John Doe
â Key Points:
fullName
is a method.this
refers to the current object (person
in this case).
đ 2. Syntax of Object Methods
const objectName = {
methodName: function() {
// code
}
};
Shorthand syntax (ES6):
const person = {
greet() {
console.log("Hello!");
}
};
đ§Ș 3. Using this
Keyword
this
refers to the object the method belongs to.
const car = {
brand: "Toyota",
showBrand() {
console.log(this.brand);
}
};
car.showBrand(); // Toyota
đ 4. Add Method After Object Creation
const student = {
name: "Anu"
};
student.sayHello = function () {
console.log("Hi, I'm " + this.name);
};
student.sayHello(); // Hi, I'm Anu
đ 5. Built-in Object Methods
Here are some methods already available on objects via JavaScript:
Method | What it Does |
---|---|
Object.keys(obj) | Returns array of keys |
Object.values(obj) | Returns array of values |
Object.entries(obj) | Returns array of [key, value] pairs |
Object.assign() | Copies properties from one object to another |
Object.hasOwnProperty() | Checks if a property exists |
Example:
const product = {
name: "Phone",
price: 999
};
console.log(Object.keys(product)); // ["name", "price"]
console.log(Object.values(product)); // ["Phone", 999]
đ 6. Private Methods (Advanced – ES6+)
Using closures or #
for private methods:
class User {
#showSecret() {
console.log("This is private");
}
accessSecret() {
this.#showSecret(); // â
Works inside
}
}
const u = new User();
u.accessSecret(); // This is private
// u.#showSecret(); â Error
đ§ Real-Life Example
const bankAccount = {
owner: "Alice",
balance: 5000,
deposit(amount) {
this.balance += amount;
console.log("Deposited:", amount);
},
withdraw(amount) {
if (amount <= this.balance) {
this.balance -= amount;
console.log("Withdrawn:", amount);
} else {
console.log("Insufficient funds");
}
},
checkBalance() {
console.log("Current Balance:", this.balance);
}
};
bankAccount.deposit(1000);
bankAccount.withdraw(3000);
bankAccount.checkBalance();
đŠ Summary
Concept | Description |
---|---|
Method | Function inside an object |
this keyword | Refers to current object |
Shorthand method | method() {} instead of method: function() {} |
Built-in methods | Object.keys() , Object.values() etc. |