Reading history

JavaScript Object Methods: entries, freeze, getters and More

6 min read 2 views

Use Object.keys, entries and fromEntries, getters and setters, Object.freeze, seal and defineProperty, and shallow vs deep copies with structuredClone.

The built-in Object helper functions turn plain objects into something you can loop over, transform and protect. Object.entries and Object.fromEntries let you map over an object as easily as an array. Getters and setters run code whenever a property is read or written. Object.freeze stops anyone changing a configuration object. This lesson tours these tools and ends with the difference between shallow and deep copies.

In this lesson you will learn

  • Object.keys, values, entries and fromEntries
  • Checking for properties with in and Object.hasOwn
  • Getters and setters with validation
  • freeze, seal and defineProperty
  • Shallow copies, deep freezing and structuredClone

You should know objects and destructuring.

Looping, Transforming and Accessors

"use strict";
const prices = { pen: 15, notebook: 80, bag: 1200 };

// keys, values and entries
console.log(Object.keys(prices), Object.values(prices));
console.log(Object.entries(prices).map(([k, v]) => `${k}=${v}`).join("&"));

// fromEntries turns pairs back into an object: transform every value
const withVat = Object.fromEntries(
  Object.entries(prices).map(([k, v]) => [k, Math.round(v * 1.15)])
);
console.log(withVat);

// Checking properties
console.log("pen" in prices, Object.hasOwn(prices, "toString"), "toString" in prices);

// Getters and setters run code when a property is read or written
const account = {
  owner: "Rina",
  _balance: 500,
  get balance() { return `${this._balance} taka`; },
  set balance(v) {
    if (v < 0) throw new RangeError("balance cannot be negative");
    this._balance = v;
  },
};
account.balance = 750;
console.log(account.balance);
try { account.balance = -10; } catch (e) { console.log(e.name + ":", e.message); }

// Object.assign copies properties into a target
const target = { a: 1 };
Object.assign(target, { b: 2 }, { a: 3 });
console.log(target);

Output

[ 'pen', 'notebook', 'bag' ] [ 15, 80, 1200 ]
pen=15&notebook=80&bag=1200
{ pen: 17, notebook: 92, bag: 1380 }
true false true
750 taka
RangeError: balance cannot be negative
{ a: 3, b: 2 }
  • Object.keys, Object.values and Object.entries return arrays of keys, values, or [key, value] pairs, so all the array methods become available.
  • Object.fromEntries does the reverse. The pattern fromEntries(entries(obj).map(...)) transforms every value of an object; here it adds 15% VAT to each price.
  • "key" in obj also finds inherited properties such as toString. Object.hasOwn(obj, "key") checks only the object’s own properties, which is usually what you want.
  • A getter (get balance()) runs when the property is read, and a setter (set balance(v)) runs when it is assigned. The setter here rejects negative balances, so invalid data cannot get in. The underscore in _balance is a naming convention meaning “internal”.
  • Object.assign(target, ...sources) copies properties into an existing object, with later sources winning.

Protecting and Copying Objects

"use strict";   // in strict mode, writing to a frozen object throws

// freeze: no changes at all
const config = Object.freeze({ apiUrl: "/api", retries: 3, limits: { max: 10 } });
try { config.retries = 5; } catch (e) { console.log("freeze:", e.constructor.name); }
config.limits.max = 99;                      // freeze is shallow
console.log(Object.isFrozen(config), config.retries, config.limits.max);

// seal: values can change, but no properties can be added or removed
const user = Object.seal({ name: "Arif", role: "student" });
user.role = "admin";
try { user.age = 21; } catch (e) { console.log("seal:", e.constructor.name); }
console.log(user);

// defineProperty: control whether a property is writable or listed
const product = { name: "Laptop" };
Object.defineProperty(product, "sku", { value: "LT-204", writable: false, enumerable: false });
console.log(product.sku, Object.keys(product), JSON.stringify(product));

// Deep freeze: freeze every nested object too
function deepFreeze(obj) {
  for (const value of Object.values(obj)) {
    if (value && typeof value === "object") deepFreeze(value);
  }
  return Object.freeze(obj);
}
const settings = deepFreeze({ theme: { dark: true } });
try { settings.theme.dark = false; } catch (e) { console.log("deep freeze:", e.constructor.name); }

// Shallow copy vs deep copy
const course = { title: "JS", topics: ["closures"] };
const shallow = { ...course }, deep = structuredClone(course);
course.topics.push("JSON");
console.log(shallow.topics, deep.topics);

Output

freeze: TypeError
true 3 99
seal: TypeError
{ name: 'Arif', role: 'admin' }
LT-204 [ 'name' ] {"name":"Laptop"}
deep freeze: TypeError
[ 'closures', 'JSON' ] [ 'closures' ]
  • Object.freeze makes an object read-only: no new properties, no deletions and no changes. In strict mode, an attempt throws a TypeError; in non-strict code it fails silently.
  • Freezing is shallow: the nested limits object could still be changed. deepFreeze walks through every nested object and freezes it too.
  • Object.seal is a middle ground: existing values can change, but properties cannot be added or removed.
  • Object.defineProperty sets property details. Here sku is read-only and not enumerable, so it is hidden from Object.keys and JSON.stringify while still being readable.
  • Spread makes a shallow copy that shares nested arrays, so it saw the new topic. structuredClone made a deep copy that did not.
  • const is different from freezing: it stops the variable being reassigned, but the object it points to can still change.

Object Helper Reference

MethodDoes
Object.keys / values / entries(o)Arrays of own enumerable keys, values or pairs
Object.fromEntries(pairs)Build an object from pairs or a Map
Object.hasOwn(o, key)Own property check
Object.assign(target, ...src)Copy properties into target
Object.freeze(o) / isFrozenMake read-only (shallow)
Object.seal(o) / isSealedFix the set of properties
Object.defineProperty(o, key, desc)Control writable, enumerable, getters
structuredClone(o)Deep copy, keeping dates, maps and sets

Common Mistakes

  1. Thinking const makes an object unchangeable.
  2. Expecting freeze to protect nested objects.
  3. A setter that assigns to its own property, such as set balance(v) { this.balance = v; }, which calls itself forever. Store the value under a different name.
  4. Using for...in without care, which also visits inherited enumerable properties. Prefer Object.entries.

Practice Exercises

Exercise 1. Keep only the subjects with marks of 80 or more from { math: 92, bangla: 75, ict: 88 }.

Show answer
const marks = { math: 92, bangla: 75, ict: 88 };
const high = Object.fromEntries(Object.entries(marks).filter(([, m]) => m >= 80));
console.log(high);   // { math: 92, ict: 88 }

Exercise 2. Add a fullName getter to { first: "Nusrat", last: "Jahan" }.

Show answer
const person = {
  first: "Nusrat",
  last: "Jahan",
  get fullName() { return `${this.first} ${this.last}`; },
};
console.log(person.fullName);   // Nusrat Jahan

Frequently Asked Questions

In what order does Object.keys return keys?

Integer-like keys come first in ascending order, then other string keys in the order they were added. If order matters, consider an array or a Map, which always keeps insertion order.

Does freezing an object make my code faster?

Not noticeably. Freeze objects to prevent accidental changes, for example in configuration or shared constants, not for speed.

Summary

  • entries and fromEntries let you map and filter objects.
  • Use Object.hasOwn to check own properties.
  • Getters and setters add computed values and validation.
  • freeze and seal are shallow; use structuredClone for deep copies.

Next: Formatting Numbers, Currency and Dates with Intl.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *