JavaScript Object Methods
Table of Contents
In the previous lesson, we learned how to create objects and store data in them. Now let’s give objects actions of their own with methods, and learn the built-in helpers that let us read every property at once.
What is an Object Method?
A method is a function stored inside an object. The object holds data in its properties, and methods are the things that object can do.
Here is a user object with a property and a method:
const user = { name: "Alex", greet() { console.log("Hello!"); },};
user.greet(); // Hello!Let’s walk through what each line does:
const user = { ... }creates an object and stores it inuser.name: "Alex"is a regular property that holds a value.greet() { ... }is a method, a key whose value is a function instead of a plain value.user.greet()runs that function: we write the object, a dot, the method name, and parentheses, just like calling any function.
Using this Inside a Method
A method often needs the object’s own data. The this keyword points to the object the method belongs to, so this.name reads the name property of that same object.
const user = { name: "Alex", greet() { console.log("Hello, " + this.name + "!"); },};
user.greet(); // Hello, Alex!Let’s trace how this resolves:
user.greet()calls the method onuser, so insidegreetthe keywordthisrefers touser.this.namereads thenameproperty of that object, which is"Alex".- The string
"Hello, " + this.name + "!"becomes"Hello, Alex!". - Change the object’s
nameand the method follows along automatically, becausethisalways points back to the object it was called on.
What does this point to?
When you call a method with object.method(), this is the object before the
dot. For user.greet(), this is user.
Reading All Properties at Once
JavaScript gives you three built-in helpers to pull data out of any object. Each one takes an object and returns an array.
| Helper | What it returns | Example | Result |
Object.keys() | An array of the property names | Object.keys(user) | ["name", "age"] |
Object.values() | An array of the property values | Object.values(user) | ["Alex", 30] |
Object.entries() | An array of [key, value] pairs | Object.entries(user) | [["name", "Alex"], ["age", 30]] |
Here they are running on a real object:
const user = { name: "Alex", age: 30,};
console.log(Object.keys(user)); // ["name", "age"]console.log(Object.values(user)); // ["Alex", 30]console.log(Object.entries(user)); // [["name", "Alex"], ["age", 30]]Let’s see what each call returns:
Object.keys(user)gives an array of just the property names:["name", "age"].Object.values(user)gives an array of just the property values:["Alex", 30].Object.entries(user)gives an array of[key, value]pairs, one small array per property:[["name", "Alex"], ["age", 30]].
Looping Over an Object
To visit every property in an object, use a for...in loop. It hands you each key one at a time, and you read the value with bracket notation.
const user = { name: "Alex", age: 30,};
for (const key in user) { console.log(key + ": " + user[key]);}// name: Alex// age: 30Let’s break down the loop:
for (const key in user)runs once for each property, putting the property name intokey.- On the first pass
keyis"name", and on the second passkeyis"age". user[key]uses bracket notation to read the value for the current key, sincekeyholds a name decided at runtime.console.log(key + ": " + user[key])prints the key and its value, givingname: Alexand thenage: 30.
You can also loop with Object.keys() and an array method, which many developers prefer because it works the same as looping over a normal array.
Object.keys(user).forEach((key) => { console.log(key + ": " + user[key]);});Let’s see how this version lines up:
Object.keys(user)turns the object’s keys into an array:["name", "age"]..forEach((key) => { ... })runs the function once per item in that array, passing the current name in askey.user[key]reads the matching value, so the output is the samename: Alexandage: 30as thefor...inversion.
A Practical Example
Say you have an object of prices and you want the total. Loop over the values and add them up.
const cart = { apple: 3, bread: 2, milk: 4,};
let total = 0;for (const value of Object.values(cart)) { total += value;}
console.log(total); // 9Let’s follow the math step by step:
Object.values(cart)pulls out just the numbers:[3, 2, 4].let total = 0sets up a running total starting at zero.for (const value of Object.values(cart))walks through that array, putting each number intovalue.total += valueadds the current number tototal, so it grows3, then5, then9.- This pattern works for any object whose values you need to combine.
Methods plus helpers
A method can use these helpers too. A summary() method might call
Object.keys(this) to list everything the object holds.
Common Mistakes to Avoid
| Mistake | Problem | Solution |
Forgetting this inside a method | name alone is not defined, so the code errors | Use this.name to read the object’s own property |
| Calling a method without parentheses | user.greet returns the function itself, not its result | Add () to run it: user.greet() |
Using Object.keys() on a non-object | Object.keys(null) throws an error | Pass a real object before reading its keys |
Try It Yourself!
- Create an object with a
nameproperty and agreet()method that prints a hello message usingthis.name. - Call the method and confirm it shows the name.
- Add an
ageproperty, then logObject.keys(),Object.values(), andObject.entries()for the object. - Build an object of numbers and use a loop to add up all its values.
What You’ve Learned
- ✅ A method is a function stored inside an object
- ✅
thislets a method read the object’s own properties - ✅
Object.keys(),Object.values(), andObject.entries()return arrays from an object - ✅
for...inloops over an object’s keys, andObject.keys()works for looping too - ✅ You can combine values from an object, such as adding up a total
What’s Next?
Now that objects can hold data and actions, let’s learn a cleaner way to pull values out of them. Let’s continue to Destructuring.