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