Objects in JavaScript are powerful because they can store not only data, but also functions.
When a function is stored inside an object, it is called a method.
Understanding object methods in JavaScript is essential if you want to work with real-world applications, APIs, and modern frameworks like React and Node.js.
What Are Object Methods in JavaScript?
An object method is simply a function that belongs to an object.
Example:
Here:
-
nameis a property -
greetis a method (because it is a function inside the object)
Creating Object Methods
You can define methods in two common ways.
Method using function keyword
Shorter method syntax (modern JavaScript)
Both are correct, but the second one is cleaner and more modern.
Using this Keyword in Object Methods
The keyword this refers to the current object.
Example:
Explanation:
-
this.namerefers to thenameproperty of the same object -
Output:
This makes methods dynamic and reusable.
Why Object Methods Are Useful
Object methods help you:
-
Perform actions related to the object
-
Keep code organized
-
Create reusable logic
-
Model real-world behavior
Example (real-world style):
This looks very similar to how real banking systems work.
Adding Methods to Existing Objects
You can add methods even after the object is created.
Objects are flexible, which makes them extremely powerful.
Built-in Object Methods (Very Common in Real Projects)
JavaScript also provides built-in object-related methods.
Object.keys()
Returns all keys (properties) of an object.
Output:
["name", "age"]
Object.values()
Returns all values of an object.
Output:
["Raj", 21]
Object.entries()
Returns key-value pairs as arrays.
Output:
[["name", "Raj"], ["age", 21]]
These are very commonly used when working with APIs and dynamic data.
Common Mistake with Arrow Functions in Object Methods
Avoid using arrow functions for methods when you need this.
Wrong:
Arrow functions do not have their own this.
Correct:
Why Object Methods Are Important in JavaScript
Mastering object methods in JavaScript helps you:
-
Build real-world applications
-
Understand APIs and JSON better
-
Use frameworks like React and Node.js
-
Write clean and structured code
-
Perform better in interviews
Almost every professional JavaScript project relies on object methods.
Conclusion
Object methods in JavaScript allow objects to do things, not just store data.
They bring behavior to your data, making your programs more powerful and organized.
Once you understand methods and the this keyword, you unlock a deeper level of JavaScript development.