Functions That Live on Objects
JavaScript Object Methods
Methods are functions stored as properties. Plus the `Object.*` helpers for iterating and copying.
What you'll learn
- Define a method on an object
- Use `Object.keys/values/entries` to iterate
- Use `Object.assign` and spread to copy/merge
A method is a function stored as an object property. Inside a
method, this refers to the object it was called on.
const user = {
name: "Ada",
greet() {
return `Hi, I'm ${this.name}`;
},
};
console.log(user.greet()); // "Hi, I'm Ada" The greet() { … } shorthand from the previous lesson is the usual
form. Don’t use arrow functions for object methods that need this
— arrows inherit this from the surrounding scope, which is rarely
what you want.
Built-in Object.* Helpers
These static methods on Object let you inspect and manipulate
objects.
Object.keys, values, entries
Turn an object into an array of keys, values, or pairs.
const user = { name: "Ada", age: 36, role: "admin" };
console.log(Object.keys(user)); // ["name", "age", "role"]
console.log(Object.values(user)); // ["Ada", 36, "admin"]
console.log(Object.entries(user));
// [["name", "Ada"], ["age", 36], ["role", "admin"]] entries is the workhorse — pair it with for..of and destructuring
to iterate cleanly:
const user = { name: "Ada", age: 36 };
for (const [key, value] of Object.entries(user)) {
console.log(`${key} = ${value}`);
}
// "name = Ada"
// "age = 36" Object.fromEntries
The inverse: takes an array of [key, value] pairs and builds an
object.
const pairs = [["name", "Ada"], ["age", 36]];
const obj = Object.fromEntries(pairs);
console.log(obj); // { name: 'Ada', age: 36 } Combined with entries it’s a great way to transform every value:
const prices = { apple: 1.50, bread: 3, cheese: 5.99 };
const doubled = Object.fromEntries(
Object.entries(prices).map(([k, v]) => [k, v * 2])
);
console.log(doubled);
// { apple: 3, bread: 6, cheese: 11.98 } Object.assign
Copy properties from one or more sources into a target. It mutates the target and returns it.
const target = { a: 1 };
const source = { b: 2, c: 3 };
Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 } In modern code, object spread is usually clearer:
const merged = { ...target, ...source }; // doesn't mutate Object.freeze
Makes an object immutable — properties can’t be added, changed, or deleted.
const config = Object.freeze({ apiUrl: "https://example.com" });
// config.apiUrl = "hacker.example"; // silently fails (throws in strict)
console.log(config.apiUrl); // "https://example.com" Object.hasOwn
The modern, safe way to ask “does this object have this OWN property?”
const user = { name: "Ada" };
console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "email")); // false
console.log(Object.hasOwn(user, "toString")); // false ← inherited, not own Up Next
Pull values out of objects with destructuring.
JavaScript Object Destructuring →