JavaScript Object Methods

Object methods are functions attached to an object, plus a family of built-in helpers on the Object constructor for inspecting and transforming any object.

Defining methods on an object

A method is simply a property whose value is a function. Modern JavaScript offers a compact shorthand where you write the name followed by parentheses and a body, without the word function or a colon. Inside the method, this points to the object it was called on, which is what lets the method work with the object's own properties.

Method shorthand and this

<!DOCTYPE html>
<html>
<body>

<h2>Method shorthand and this</h2>

<script>
const rectangle = {
  width: 4,
  height: 3,
  area() {
    return this.width * this.height;
  },
  describe() {
    return `A ${this.width} by ${this.height} rectangle`;
  }
};

console.log(rectangle.area());     // 12
console.log(rectangle.describe()); // "A 4 by 3 rectangle"
</script>

</body>
</html>
Note: Avoid arrow functions for methods that rely on this. Arrow functions do not have their own this, so this.width inside an arrow method would not refer to the object. Use the shorthand or a regular function for methods.

Built-in Object methods

The Object constructor provides static helpers that operate on any object. The most used are Object.keys, Object.values, and Object.entries, which turn an object's contents into arrays so you can loop over or transform them with array methods. Object.assign and the spread syntax help you copy and merge objects.

MethodReturnsExample result
Object.keys(obj)Array of the keys["name", "age"]
Object.values(obj)Array of the values["Lin", 28]
Object.entries(obj)Array of [key, value] pairs[["name","Lin"],["age",28]]
Object.assign(target, src)The target after copyingmerged object
Object.freeze(obj)The now-immutable objectsame object, locked

Looping over an object with entries

<!DOCTYPE html>
<html>
<body>

<h2>Looping over an object with entries</h2>

<script>
const scores = { math: 90, science: 85, history: 78 };

for (const [subject, score] of Object.entries(scores)) {
  console.log(`${subject}: ${score}`);
}
// math: 90
// science: 85
// history: 78

const total = Object.values(scores).reduce((a, b) => a + b, 0);
console.log(total); // 253
</script>

</body>
</html>

Copying and merging objects

Because objects are references, copying one with a plain assignment does not create a separate object. To make a shallow copy, use Object.assign with an empty target or the spread syntax. Both copy the top-level properties into a new object; merging works by listing later sources whose keys overwrite earlier ones.

Merging with spread

<!DOCTYPE html>
<html>
<body>

<h2>Merging with spread</h2>

<script>
const defaults = { theme: "light", fontSize: 14 };
const userPrefs = { fontSize: 16 };

const settings = { ...defaults, ...userPrefs };
console.log(settings); // { theme: "light", fontSize: 16 }

// Object.assign does the same into a new object
const copy = Object.assign({}, defaults);
console.log(copy); // { theme: "light", fontSize: 14 }
</script>

</body>
</html>
Note: Both spread and Object.assign make a shallow copy. Nested objects are still shared by reference, so changing a nested value in the copy also changes it in the original.
  • Define methods with the concise shorthand: name() { ... }.
  • Object.keys, Object.values, and Object.entries bridge objects to array methods.
  • Use spread ({...obj}) or Object.assign to make shallow copies and merge objects.
  • Object.freeze prevents further changes to an object's top-level properties.