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,entriesandfromEntries- Checking for properties with
inandObject.hasOwn - Getters and setters with validation
freeze,sealanddefineProperty- 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¬ebook=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.valuesandObject.entriesreturn arrays of keys, values, or[key, value]pairs, so all the array methods become available.Object.fromEntriesdoes the reverse. The patternfromEntries(entries(obj).map(...))transforms every value of an object; here it adds 15% VAT to each price."key" in objalso finds inherited properties such astoString.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_balanceis 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.freezemakes an object read-only: no new properties, no deletions and no changes. In strict mode, an attempt throws aTypeError; in non-strict code it fails silently.- Freezing is shallow: the nested
limitsobject could still be changed.deepFreezewalks through every nested object and freezes it too. Object.sealis a middle ground: existing values can change, but properties cannot be added or removed.Object.definePropertysets property details. Hereskuis read-only and not enumerable, so it is hidden fromObject.keysandJSON.stringifywhile still being readable.- Spread makes a shallow copy that shares nested arrays, so it saw the new topic.
structuredClonemade a deep copy that did not. constis different from freezing: it stops the variable being reassigned, but the object it points to can still change.
Object Helper Reference
| Method | Does |
|---|---|
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) / isFrozen | Make read-only (shallow) |
Object.seal(o) / isSealed | Fix the set of properties |
Object.defineProperty(o, key, desc) | Control writable, enumerable, getters |
structuredClone(o) | Deep copy, keeping dates, maps and sets |
Common Mistakes
- Thinking
constmakes an object unchangeable. - Expecting
freezeto protect nested objects. - 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. - Using
for...inwithout care, which also visits inherited enumerable properties. PreferObject.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
entriesandfromEntrieslet you map and filter objects.- Use
Object.hasOwnto check own properties. - Getters and setters add computed values and validation.
freezeandsealare shallow; usestructuredClonefor deep copies.
