Tutorials JavaScript Object Methods
Ch 35 / 78
Chapter 36 Intermediate 8 min read JavaScript

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.

What you'll learn
Defining methods — all three syntactic forms
this inside methods — what it refers to
Object.keys, Object.values, Object.entries
Object.assign and the spread operator for merging
Object.freeze, Object.seal — immutability
hasOwnProperty, in operator, computed properties

Three Kinds of Object Methods

JavaScript object methods fall into three categories. Understanding the difference helps you pick the right tool every time:

obj.method()
Instance Method
A function defined as a property of a specific object or its prototype. Called on an instance. Has access to this, which refers to the calling object.
Use when: the behaviour is tied to a particular object's data — user.greet(), cart.total().
Object.method()
Static / Built-in
Methods called directly on the Object constructor itself. They operate on an object passed as an argument. No instance needed.
Use when: transforming, inspecting, copying or freezing plain objects — Object.keys(obj).
computed / shorthand
Modern Shorthand
ES6 shorthand method syntax (greet() {}) and computed property names ([key]()) for cleaner, more concise object literals.
Use when: writing modern JS — shorthand is the standard in classes, module exports, and 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:

const obj = {
  name: "Alice",
  greet() {                 // ← ES6 shorthand method
    return `Hello, ${this.name}`;
  }
};
greet — the method name (property key) this — refers to the object the method is called on ES6 shorthand: omit the colon and function keyword Arrow functions as methods lose this — use shorthand instead
Three ways to define a method
1 Function expression — greet: function() {} (old style)
2 ES6 shorthand — greet() {} (preferred modern style)
3 Arrow function — greet: () => {} (avoid as method — no own this)
4 Computed name — [dynamicKey]() {} — key from variable
this inside methods — watch out
✓ obj.method() — this is the object before the dot
✗ Arrow method — inherits outer this, NOT the object
✗ Destructured — const { greet } = obj; greet() loses this
✓ bind/call/apply — explicitly set this when needed
JavaScript — Defining Object Methods
// ── 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 this
Never Use Arrow Functions as Object Methods
Arrow functions do not have their own this. 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:

JavaScript — this Inside Object Methods
// ── 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 this

Object.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:

Object.keys / values / entries
K Object.keys(obj) — array of own enumerable property names
V Object.values(obj) — array of own enumerable values
E Object.entries(obj) — array of [key, value] pairs
F Object.fromEntries(pairs) — rebuild object from entries
What each returns
✓ Object.keys({a:1,b:2}) → ["a","b"]
✓ Object.values({a:1,b:2}) → [1,2]
✓ Object.entries({a:1}) → [["a",1]]
✓ All three return arrays — iterate with for...of or forEach
JavaScript — Object.keys, values, entries
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)
JavaScript — Object.assign & Spread
// ── 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 independent
Shallow vs Deep Copy
Both Object.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:

Object.freeze(obj)
Makes all properties non-writable and non-configurable. No new properties, no deletions, no value changes. Perfect for constants. Shallow — nested objects are not frozen.
Object.seal(obj)
Prevents adding or removing properties but allows changing existing values. Useful when you want a fixed shape but mutable data.
Object.hasOwn(obj, key)
Modern (ES2022) safe check whether an object has a property as its own (not inherited). Safer than obj.hasOwnProperty(key).
"key" in obj
Returns true if the property exists on the object or in its prototype chain. Use Object.hasOwn for own-only checks.
JavaScript — freeze, seal, hasOwn, in
// ── 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 properties

Real-World Use Cases

Object methods appear in practically every JavaScript codebase. Here are the situations you'll reach for them most often:

Config / Settings Merge
Merge user preferences over defaults with spread: { ...defaults, ...user }. The last key wins.
Object.assign / spread
Iterate Object Data
Loop over API response objects with Object.entries to build tables, lists, or form fields dynamically.
Object.entries
Immutable Constants
Use Object.freeze on config objects and enums to prevent accidental mutation throughout your app.
Object.freeze
Redux-Style State Updates
Produce new state without mutating old state: { ...state, count: state.count + 1 } — pure function pattern.
spread
Builder / Chainable API
Methods that return this enable fluent chaining: obj.setName("X").setAge(30).build().
instance method
Safe Property Check
Use Object.hasOwn(obj, key) instead of in when you only want to check the object's own properties, not inherited ones.
Object.hasOwn
⚡
Free Resource
Download our JavaScript Cheat Sheet
Object methods, this binding, spread, freeze & all built-in utilities — one printable page.
Get Sheet

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.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These object method patterns appear constantly in modern JavaScript, React, Node.js, and API-driven codebases:

JavaScript — Object Method Recipes
// ── 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) { ... }
Quick Check
What does this refer to inside an ES6 shorthand method called as obj.greet()?
Quick Check
What does Object.entries({ a: 1, b: 2 }) return?
Quick Check
After calling Object.freeze(obj), what happens when you try to change a property?
Chapter Summary
  • 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 old greet: function() {}.
  • this inside a regular method refers to the object before the dot at call time. Never use arrow functions as object methods — they inherit this from the enclosing scope instead.
  • Methods can call other methods via this and implement method chaining by returning this at 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 and Object.assign are shallow — use structuredClone() for deep copies.
  • Object.freeze makes an object fully immutable. Object.seal allows 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 obj when inherited properties should also match, and Object.fromEntries to rebuild objects from entries transformations.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel