iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Object Methods

A method is a function stored as an object property. Inside it, this refers to the object the method was called on.

Defining methods

JS
const user = {
  name: "Ada",

  // Shorthand method (recommended)
  greet() {
    return `Hi, ${this.name}!`;
  },

  // Same thing, long form
  greetLong: function () { return `Hi, ${this.name}!`; },

  // ⚠️ Arrow function does NOT bind its own `this`
  greetArrow: () => `Hi, ${this.name}!`,   // this is the outer scope
};

Useful static helpers on Object

MethodWhat it does
Object.keys(obj)Own enumerable property names.
Object.values(obj)Own enumerable values.
Object.entries(obj)[key, value] pairs.
Object.fromEntries(pairs)Reverse of entries.
Object.assign(target, src)Mutating shallow merge.
{ …src }Non-mutating shallow merge.
Object.freeze(obj)Read-only (shallow).
Object.create(proto)New object with the given prototype.
Object.hasOwn(obj, key)Own-property check (modern).
structuredClone(obj)Deep clone — handles Date, Set, Map, cycles.

Idiomatic recipes

JS
// Filter keys
const safe = Object.fromEntries(
  Object.entries(user).filter(([k]) => k !== "password")
);

// Map values
const doubled = Object.fromEntries(
  Object.entries(scores).map(([k, v]) => [k, v * 2])
);

// Pick specific keys
const pick = (obj, keys) =>
  Object.fromEntries(keys.filter(k => k in obj).map(k => [k, obj[k]]));
Tip: Methods that need this bound to their object should use the shorthand form, not arrow functions. Arrows ignore method-call binding by design.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Object Methods!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Iterate every (key, value) pair.

for (const [k, v] of Object. (user)) { /* ... */ }

Test yourself

Q1. Get an array of [key, value] pairs with…
Q2. Method shorthand `{ greet() {…} }` and `{ greet: function() {…} }` differ in…
Q3. Deep-clone plain data with…

Discussion

Loading…