Object Methods
In JavaScript, methods are functions stored
as properties of an object. They give objects behaviour, not just data.
This chapter covers how to define methods in all syntactic forms, how
this works inside a method, and all the
powerful built-in static methods —
Object.keys,
Object.values,
Object.entries,
Object.assign,
Object.freeze and more —
that you'll use every day in real JavaScript code.
this inside methods — what it refers
toThree Kinds of Object Methods
JavaScript object methods fall into three categories. Understanding the difference helps you pick the right tool every time:
this, which refers to the
calling object.user.greet(), cart.total().Object constructor
itself. They operate on an object passed as an argument. No instance needed.Object.keys(obj).greet() {}) and computed
property names ([key]()) for cleaner, more concise object literals.Defining Methods — All Syntactic Forms
A method is simply a function assigned to an object property. JavaScript gives you three ways to write this, with ES6 shorthand being the modern standard:
name: "Alice",
greet() { // ← ES6 shorthand method
return `Hello, ${this.name}`;
}
};
greet: function() {} (old style)
greet() {}
(preferred modern style)
greet: () => {} (avoid as method — no own this)
[dynamicKey]() {} — key from variable
this is the
object before the dot
this, NOT the object
const { greet } = obj; greet() loses this
this when needed
// ── 1. Function expression (old style) ───────────────────────
const user1 = {
name: "Alice",
greet: function() {
return `Hello, I'm ${this.name}`;
}
};
// ── 2. ES6 shorthand (modern, preferred) ─────────────────────
const user2 = {
name: "Bob",
greet() {
return `Hello, I'm ${this.name}`;
},
fullInfo() {
return `${this.name} — ${this.role}`;
}
};
// ── 3. Arrow as method — ⚠ this is NOT the object ────────────
const user3 = {
name: "Carol",
greet: () => `Hello, I'm ${this?.name}` // ✗ this = outer scope, not user3
};
// ── 4. Computed method name ───────────────────────────────────
const action = "run";
const robot = {
[action]() { return "Running!"; }
};
robot.run(); // "Running!"
console.log(user2.greet()); // "Hello, I'm Bob"
console.log(user3.greet()); // "Hello, I'm undefined" — arrow lost thisthis.
When used as a method, this refers to the
enclosing scope (often undefined in strict mode
or window in browsers) — not the object. Always use
ES6 shorthand syntax (greet() {}) for methods
that need to access the object's own data.
The this Keyword Inside Methods
this inside a regular method
refers to the object that the method was called on — the object
before the dot. It gives the method access to all the object's own properties,
enabling self-referential logic like this.name
or this.price * this.qty:
// ── this refers to the calling object ────────────────────────
const product = {
name: "Laptop",
price: 45000,
qty: 3,
total() { return this.price * this.qty; },
describe() { return `${this.name}: ₹${this.total()}`; }
};
product.total(); // 135000 — this = product
product.describe(); // "Laptop: ₹135000"
// ── Methods calling other methods via this ────────────────────
const counter = {
count: 0,
increment() { this.count++; },
decrement() { this.count--; },
reset() { this.count = 0; },
value() { return this.count; }
};
counter.increment();
counter.increment();
counter.increment();
counter.decrement();
counter.value(); // 2
// ── Method chaining — return this ────────────────────────────
const builder = {
parts: [],
add(part) { this.parts.push(part); return this; },
build() { return this.parts.join(" + "); }
};
builder.add("CPU").add("RAM").add("SSD").build();
// "CPU + RAM + SSD" — method chaining via return thisObject.keys, Object.values & Object.entries
These three static utility methods are the most-used Object methods in day-to-day JavaScript. They convert a plain object's own enumerable properties into arrays you can iterate, map, and filter:
[key, value] pairs
Object.keys({a:1,b:2}) →
["a","b"]
Object.values({a:1,b:2}) →
[1,2]
Object.entries({a:1}) →
[["a",1]]
for...of
or forEach
const scores = { alice: 95, bob: 82, carol: 77 };
// ── Object.keys ───────────────────────────────────────────────
Object.keys(scores); // ["alice", "bob", "carol"]
// ── Object.values ─────────────────────────────────────────────
Object.values(scores); // [95, 82, 77]
// ── Object.entries — iterate key+value ───────────────────────
Object.entries(scores); // [["alice",95],["bob",82],["carol",77]]
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}
// ── Practical uses ────────────────────────────────────────────
const avg = Object.values(scores).reduce((a, b) => a + b) / Object.keys(scores).length;
// 84.67 — average score
const passing = Object.fromEntries(
Object.entries(scores).filter(([_, v]) => v >= 80)
);
// { alice: 95, bob: 82 } — only students who passed
// ── Check property count ──────────────────────────────────────
Object.keys(scores).length; // 3 — number of properties
Object.keys({}).length === 0; // true — empty object check
Object.assign & Spread Operator
Copying and merging objects are essential patterns in JavaScript.
Object.assign and the
spread operator ({ ...obj })
both perform shallow copies — but the spread syntax is cleaner and preferred
in modern code:
| Method | Syntax | Mutates target? | Best for |
|---|---|---|---|
| Object.assign | Object.assign(target, src) |
Yes | Polyfill-safe copy, mutate in place |
| Spread | { ...src } |
No | Modern immutable merge, React state |
| structuredClone | structuredClone(obj) |
No | Deep copy — nested objects (ES2022) |
// ── Object.assign — copies into target ───────────────────────
const defaults = { theme: "dark", lang: "en", size: 14 };
const userPrefs = { theme: "light", size: 16 };
const config = Object.assign({}, defaults, userPrefs);
// { theme:"light", lang:"en", size:16 } — userPrefs wins
// ── Spread (preferred in modern code) ────────────────────────
const config2 = { ...defaults, ...userPrefs };
// Same result — cleaner syntax
// ── Shallow clone ─────────────────────────────────────────────
const user = { name: "Alice", age: 28 };
const clone = { ...user }; // { name:"Alice", age:28 }
clone.name = "Bob"; // original user.name unchanged ✓
// ── Override a single property (immutable update) ────────────
const updated = { ...user, age: 29 }; // { name:"Alice", age:29 }
// ── Adding properties on spread ───────────────────────────────
const withRole = { ...user, role: "admin" };
// { name:"Alice", age:28, role:"admin" }
// ── Deep clone (ES2022) ───────────────────────────────────────
const deep = { a: { b: { c: 42 } } };
const deepClone = structuredClone(deep); // fully independentObject.assign and spread do a shallow copy
— nested objects are still shared by reference. Modifying a nested property
in the clone will affect the original. Use structuredClone(obj)
(ES2022) or a library like Lodash's _.cloneDeep when you need
true independence of nested data.
Object.freeze, Object.seal & Property Checks
JavaScript gives you control over how mutable an object is.
Object.freeze makes it fully immutable,
Object.seal prevents adding or removing
properties, and several methods help you safely check for property existence:
obj.hasOwnProperty(key).true if the property exists on the object
or in its prototype chain. Use Object.hasOwn for own-only checks.
// ── Object.freeze ─────────────────────────────────────────────
const CONFIG = Object.freeze({
API_URL: "https://api.example.com",
TIMEOUT: 5000,
DEBUG: false
});
CONFIG.TIMEOUT = 9999; // ✗ silently ignored (strict mode: TypeError)
CONFIG.NEW_KEY = "x"; // ✗ silently ignored
Object.isFrozen(CONFIG); // true
// ── Object.seal ───────────────────────────────────────────────
const shape = Object.seal({ color: "red", size: 10 });
shape.color = "blue"; // ✓ allowed — existing value changed
shape.weight = 5; // ✗ ignored — can't add new properties
// ── Property existence checks ─────────────────────────────────
const user = { name: "Alice", age: 28 };
"name" in user; // true — own + inherited
"toString" in user; // true — inherited from Object.prototype!
Object.hasOwn(user, "name"); // true — own only ✓
Object.hasOwn(user, "toString"); // false — inherited, not own ✓
// ── Object.isFrozen / isSealed ────────────────────────────────
Object.isFrozen(CONFIG); // true
Object.isSealed(shape); // true
Object.isExtensible(user); // true — can still add propertiesReal-World Use Cases
Object methods appear in practically every JavaScript codebase. Here are the situations you'll reach for them most often:
{ ...defaults, ...user }. The last key wins.
Object.entries to
build tables, lists, or form fields dynamically.
Object.freeze on config objects and enums to
prevent accidental mutation throughout your app.
{ ...state, count: state.count + 1 } — pure function pattern.
return this enable fluent chaining:
obj.setName("X").setAge(30).build().
Object.hasOwn(obj, key) instead of in
when you only want to check the object's own properties, not inherited ones.
Try It — Live Editor
Experiment with object methods below. Modify the objects, call
built-in static methods, and observe how this
and merging behave — all without leaving this page.
Common Patterns & Recipes
These object method patterns appear constantly in modern JavaScript, React, Node.js, and API-driven codebases:
// ── Rename object keys ────────────────────────────────────────
const raw = { first_name: "Alice", last_name: "Smith" };
const renamed = Object.fromEntries(
Object.entries(raw).map(([k, v]) => [k.replace(/_(\w)/g, (_, c) => c.toUpperCase()), v])
); // { firstName:"Alice", lastName:"Smith" }
// ── Invert key-value pairs ────────────────────────────────────
const map = { a: 1, b: 2, c: 3 };
const inverted = Object.fromEntries(
Object.entries(map).map(([k, v]) => [v, k])
); // { 1:"a", 2:"b", 3:"c" }
// ── Pick specific keys from an object ─────────────────────────
const pick = (obj, keys) =>
Object.fromEntries(keys.map(k => [k, obj[k]]));
pick({ a: 1, b: 2, c: 3 }, ["a", "c"]); // { a:1, c:3 }
// ── Omit specific keys ────────────────────────────────────────
const omit = (obj, keys) =>
Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));
omit({ a: 1, b: 2, c: 3 }, ["b"]); // { a:1, c:3 }
// ── Transform all values ──────────────────────────────────────
const prices = { apple: 100, mango: 200, banana: 50 };
const discounted = Object.fromEntries(
Object.entries(prices).map(([k, v]) => [k, v * 0.9])
); // { apple:90, mango:180, banana:45 }
// ── Enum pattern with freeze ──────────────────────────────────
const Status = Object.freeze({
PENDING: "pending",
ACTIVE: "active",
INACTIVE: "inactive"
});
// Use as: if (user.status === Status.ACTIVE) { ... }this refer to inside an ES6 shorthand method called as
obj.greet()?
Object.entries({ a: 1, b: 2 }) return?Object.freeze(obj), what happens when you try to
change a property?- A method is a function stored as a property of an object. The preferred
syntax is the ES6 shorthand (
greet() {}) — shorter, cleaner, and equivalent to the oldgreet: function() {}. thisinside a regular method refers to the object before the dot at call time. Never use arrow functions as object methods — they inheritthisfrom the enclosing scope instead.- Methods can call other methods via
thisand implement method chaining by returningthisat the end of each mutating method. Object.keys(obj)returns own enumerable property names.Object.values(obj)returns their values.Object.entries(obj)returns[key, value]pairs — all as arrays ready to iterate.- Use spread syntax (
{ ...defaults, ...overrides }) for clean, immutable object merging. Both spread andObject.assignare shallow — usestructuredClone()for deep copies. Object.freezemakes an object fully immutable.Object.sealallows value changes but prevents adding/removing properties. Both are shallow — nested objects remain mutable.- Use
Object.hasOwn(obj, key)for safe own-property checks,"key" in objwhen inherited properties should also match, andObject.fromEntriesto rebuild objects fromentriestransformations.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.