JavaScript Functions and Methods: A Topic-by-Topic Reference · Lesson 7 of 12

Lesson 7: Object Methods

Object.keys, values, entries, assign, fromEntries, freeze, spread, destructuring, optional chaining, nullish coalescing and copying.

Lesson 7: Object Methods

An object stores named values (properties). The Object built-in has helper functions for listing, copying and protecting objects.

Listing

Object.keys, values, entries

Arrays of the property names, the values, or the [name, value] pairs.

const user = { name: "Sita", age: 19, city: "Pokhara" };
console.log(Object.keys(user));
console.log(Object.values(user));
console.log(Object.entries(user));
for (const [k, v] of Object.entries(user)) console.log(k, "=", v);

Output:

[ 'name', 'age', 'city' ]
[ 'Sita', 19, 'Pokhara' ]
[ [ 'name', 'Sita' ], [ 'age', 19 ], [ 'city', 'Pokhara' ] ]
name = Sita
age = 19
city = Pokhara

Object.fromEntries(pairs)

The opposite of entries: build an object from pairs. Combine with entries and map to transform an object.

const prices = { pen: 10, book: 250 };
const doubled = Object.fromEntries(Object.entries(prices).map(([k, v]) => [k, v * 2]));
console.log(doubled);
console.log(Object.fromEntries([["a", 1], ["b", 2]]));

Output:

{ pen: 20, book: 500 }
{ a: 1, b: 2 }

Checking and reading

in, hasOwn, hasOwnProperty

Does the object have this property? Object.hasOwn ignores inherited ones.

const o = { a: 1, b: undefined };
console.log("a" in o, "z" in o, "toString" in o);
console.log(Object.hasOwn(o, "b"), Object.hasOwn(o, "toString"));
console.log(o.b === undefined, o.z === undefined);

Output:

true false true
true false
true true

Optional chaining ?. and nullish ??

?. stops safely when something in a chain is missing; ?? supplies a default only for null/undefined (unlike ||, it keeps 0 and "").

const user = { profile: { city: "Pokhara" }, score: 0 };
console.log(user.profile?.city);
console.log(user.address?.street);
console.log(user.score || 10, user.score ?? 10);
console.log(user.getName?.());

Output:

Pokhara
undefined
10 0
undefined

Changing

Add, change, delete

Assignment adds or changes; delete removes.

const o = { a: 1 };
o.b = 2;
o["c d"] = 3;
o.a = 100;
delete o.b;
console.log(o);

Output:

{ a: 100, 'c d': 3 }

Computed property names

Use a variable as the property name with [ ].

const key = "colour";
const o = { [key]: "blue", [`${key}Count`]: 2 };
console.log(o);

Output:

{ colour: 'blue', colourCount: 2 }

Shorthand properties and methods

When the variable name equals the property name you can write it once.

const name = "Ram", age = 17;
const person = { name, age, greet() { return `Hi, I am ${this.name}`; } };
console.log(person, person.greet());

Output:

{ name: 'Ram', age: 17, greet: [Function: greet] } Hi, I am Ram

Copying and merging

Spread { ...obj } and Object.assign

Copy an object, or merge several (later ones win).

const defaults = { theme: "light", size: 10 };
const custom = { size: 14 };
console.log({ ...defaults, ...custom });
console.log(Object.assign({}, defaults, custom, { extra: true }));
const copy = { ...defaults };
copy.size = 99;
console.log(defaults.size);

Output:

{ theme: 'light', size: 14 }
{ theme: 'light', size: 14, extra: true }
10

Spread and Object.assign make shallow copies: nested objects are shared. For a deep copy use structuredClone(obj).

Destructuring objects

Pull properties into variables, with renaming and defaults.

const user = { name: "Sita", age: 19, city: "Pokhara" };
const { name, age: years, country = "Nepal" } = user;
console.log(name, years, country);
const { city, ...others } = user;
console.log(city, others);
function show({ name, age = 0 }) { return `${name} (${age})`; }
console.log(show({ name: "Ram" }));

Output:

Sita 19 Nepal
Pokhara { name: 'Sita', age: 19 }
Ram (0)

Protecting

Object.freeze, seal, isFrozen

freeze makes an object read-only (shallow). In strict mode, changes throw an error; otherwise they are silently ignored.

"use strict";
const config = Object.freeze({ api: "v1", nested: { n: 1 } });
try { config.api = "v2"; } catch (e) { console.log(e.constructor.name); }
config.nested.n = 2;
console.log(config, Object.isFrozen(config));

Output:

TypeError
{ api: 'v1', nested: { n: 2 } } true

Object.getOwnPropertyNames and defineProperty

Lower-level tools for controlling properties.

const o = {};
Object.defineProperty(o, "id", { value: 7, enumerable: false });
console.log(o.id, Object.keys(o), Object.getOwnPropertyNames(o));

Output:

7 [] [ 'id' ]

Comparing and JSON

Comparing objects

Two objects are equal only if they are the same object. To compare content, compare their JSON or write a helper.

console.log({ a: 1 } === { a: 1 });
console.log(JSON.stringify({ a: 1 }) === JSON.stringify({ a: 1 }));
const a = { x: 1 }, b = a;
console.log(a === b);

Output:

false
true
true

this, getters and setters, classes

A small class with a getter.

class Rectangle {
  constructor(w, h) { this.w = w; this.h = h; }
  get area() { return this.w * this.h; }
  describe() { return `${this.w} x ${this.h}`; }
}
const r = new Rectangle(3, 4);
console.log(r.area, r.describe());

Output:

12 3 x 4

Try it yourself

  1. Count how many properties an object has.
  2. Swap the keys and values of an object with entries and fromEntries.
  3. Merge two settings objects, with the second overriding the first.

Next lesson: Set and Map.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 7: Object Methods | MeroSir