Object Methods

Published by Brayan K

The static Object methods — keys, values, entries, assign, and freeze — let you inspect, transform, merge, and protect plain objects without manual loops.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Choose which properties you intend to inspect

An object can have inherited properties, non-enumerable own properties and symbol keys. There is no universal “all properties” list: first decide which of those groups your task needs. For a table of ordinary public fields, Object.entries is useful because each key stays paired with its value. For an inspection tool, Reflect.ownKeys has a different job.

// Build an object with inherited, hidden and symbol fields.
const marker = Symbol("marker");
const item = Object.create({ inherited: "prototype" });
item.name = "Notebook";
item[marker] = "symbol field";
Object.defineProperty(item, "internal", { value: 42 });
// Compare the deliberately different own-property views.
console.log(JSON.stringify(Object.keys(item)));
console.log(JSON.stringify(Object.values(item)));
console.log(JSON.stringify(Object.entries(item)));
console.log(Reflect.ownKeys(item).map(key => typeof key === "symbol" ? String(key) : key).join(", "));
console.log(Object.hasOwn(item, "inherited"), "inherited" in item);

// ✅ Expected output:
// ["name"]
// ["Notebook"]
// [["name","Notebook"]]
// name, internal, Symbol(marker)
// false true

keys, values and entries include own enumerable string-keyed properties. Reflect.ownKeys includes own string and symbol keys whether enumerable or not; it still excludes inherited properties. Accessor reads can run code when values or entries collect values. Getters, Setters & Property Descriptors owns accessor and descriptor behavior.

const item = {};
item.zebra = 1;
item["10"] = 10;
item["2"] = 2;
item["01"] = 1;
item.apple = 3;
console.log(Object.keys(item).join(", "));
console.log(JSON.stringify(Object.entries(item).map(([key, value]) => [key, value * 2])));

// ✅ Expected output:
// 2, 10, zebra, 01, apple
// [["2",4],["10",20],["zebra",2],["01",2],["apple",6]]

These ordinary own-key operations put array-index keys in ascending numeric order, then other string keys in creation order. The string "01" is not an array-index key. Symbols follow string keys in Reflect.ownKeys. Do not use an object when your requirement is an arbitrary insertion order across numeric-looking keys; Map & Set covers the alternative collection.

Transform entries without confusing replacement with merging

const result = Object.fromEntries([
  ["count", 2],
  ["count", 7],
  ["__proto__", "ordinary data"]
]);
console.log(result.count);
console.log(Object.hasOwn(result, "__proto__"));
console.log(result.__proto__);
console.log(Object.getPrototypeOf(result) === Object.prototype);

// ✅ Expected output:
// 7
// true
// ordinary data
// true

fromEntries constructs a new ordinary object. It does not reject duplicate keys, recursively combine values or preserve the input object’s prototype and descriptors. A "__proto__" entry is defined as an own data property by this operation. That fact is specific to this construction step; it does not make arbitrary later merges or untrusted property paths safe.

const stock = { pens: 0, pads: 4, folders: 2 };
const available = Object.fromEntries(Object.entries(stock).filter(([, count]) => count > 0));
console.log(JSON.stringify(available));
console.log(JSON.stringify(stock));

// ✅ Expected output:
// {"pads":4,"folders":2}
// {"pens":0,"pads":4,"folders":2}

The source object still exists. The new object contains selected values, so a nested object value would still be shared. Deep Copy vs Shallow Copy & Data Structures owns copying nested graphs; the object methods here do not promise that.

Object.assign writes into a target and can stop halfway

const target = { settings: { theme: "light", size: 20 } };
const returned = Object.assign(target, { settings: { theme: "dark" } }, { active: true });
console.log(returned === target);
console.log(JSON.stringify(target));

// ✅ Expected output:
// true
// {"settings":{"theme":"dark"},"active":true}
let reads = 0;
const source = { get score() { reads++; return 7; } };
const log = [];
const target = { set score(value) { log.push(value); } };
Object.assign(target, source);
const copied = { ...source };
console.log(reads, JSON.stringify(log));
console.log(Object.getOwnPropertyDescriptor(copied, "score").value);
console.log(Object.hasOwn(Object.getOwnPropertyDescriptor(copied, "score"), "get"));

// ✅ Expected output:
// 2 [7]
// 7
// false

Both operations read enumerable source values, which may invoke getters. Object.assign uses ordinary assignment on the target, so a target setter may run. Object spread creates own data properties in its new object. Neither copies getter/setter definitions as definitions. Both also include enumerable symbol keys, even though Object.keys does not list them.

const target = {};
Object.defineProperty(target, "locked", { value: 1, writable: false });
try {
  Object.assign(target, { first: 2, locked: 3, last: 4 });
} catch (error) {
  console.log(error.name);
}
console.log(target.first, target.locked, Object.hasOwn(target, "last"));

// ✅ Expected output:
// TypeError
// 2 1 false
Object.assign(Object.freeze({ count: 1 }), { count: 2 });

// ✅ Expected error:
// TypeError: Cannot assign to read only property 'count' of object '#<Object>'

The successful earlier write remains after the later failure. If all-or-nothing construction matters, validate the input first and build a fresh result that you only return after success. This does not make arbitrary getters pure: the exercise below deliberately accepts ordinary data arrays, not hostile proxy objects.

Protection applies to the object you actually protect

for (const protect of [Object.preventExtensions, Object.seal, Object.freeze]) {
  const value = protect({ count: 1 });
  console.log(
    Reflect.set(value, "extra", 2),
    Reflect.set(value, "count", 3),
    Reflect.deleteProperty(value, "count"),
    Object.isExtensible(value),
    Object.isSealed(value),
    Object.isFrozen(value)
  );
}

// ✅ Expected output:
// false true true false true true
// false true false false true false
// false false false false true true

preventExtensions blocks new own properties. seal also makes existing own properties non-configurable. freeze additionally makes own data properties non-writable. These operations return the same object. In the first row, successful deletion removes the only own property before the final checks: that empty, non-extensible object is now both sealed and frozen. The original count property was still writable and deletable. Reflect operations report a refused ordinary change as false; direct assignments to non-writable properties throw in strict code. An accessor setter is a different kind of property and can still change separate state even on a frozen object.

const settings = Object.freeze({ panel: { open: false } });
settings.panel.open = true;
console.log(settings.panel.open);
console.log(Object.isFrozen(settings), Object.isFrozen(settings.panel));

// ✅ Expected output:
// true
// true false
const lookup = Object.create(null);
lookup.hasOwnProperty = "ordinary value";
lookup.answer = undefined;
console.log(Object.hasOwn(lookup, "answer"));
console.log(Object.hasOwn(lookup, "missing"));
console.log(Object.getPrototypeOf(lookup) === null);

// ✅ Expected output:
// true
// false
// true

A value of undefined does not mean a property is absent. Object.hasOwn asks about ownership directly and works for null-prototype objects or objects with a field named hasOwnProperty. A null prototype removes inherited methods; it is a data-shape choice, not an authorization boundary.

Guided exercise: retain positive stock entries

Complete the three blanks. The hints are literal replacements. Preserve the original object and return a new object containing only positive counts.

const stock = { red: 0, blue: 3, green: 1 };
const pairs = Object.___(stock); // 👉 replace ___ with entries
const selected = pairs.filter(([, count]) => ___); // 👉 replace ___ with count > 0
const result = Object.___(selected); // 👉 replace ___ with fromEntries
console.log(JSON.stringify(result));
console.log(Object.keys(stock).length);

// ✅ Expected output:
// {"blue":3,"green":1}
// 3

Build brief: a frozen lookup with explicit key rules

Write makeLookup(pairs) for ordinary data arrays. Accept a dense array of at most 50 dense two-entry arrays. Keys must contain 1–24 lowercase ASCII letters or underscores; values must be safe integers. Reject duplicate keys, including repeated "__proto__". Validate the entire input before constructing the returned lookup.

Return a frozen null-prototype object whose selected keys are enumerable, non-writable and non-configurable own data properties. Normalize negative zero to zero. Preserve input order for these non-numeric keys and do not mutate any input array. Invalid shape, key, value or duplication throws TypeError with the messages shown in the checked solution. Getter/proxy side effects are outside this ordinary-data contract.

function makeLookup(pairs) {
  if (!Array.isArray(pairs) || pairs.length > 50) throw new TypeError("expected at most 50 pairs");
  const rows = [];
  const seen = new Set();
  for (let i = 0; i < pairs.length; i++) {
    if (!Object.hasOwn(pairs, i)) throw new TypeError("pairs must be dense");
    const pair = pairs[i];
    if (!Array.isArray(pair) || pair.length !== 2 || !Object.hasOwn(pair, 0) || !Object.hasOwn(pair, 1)) {
      throw new TypeError("each pair needs two entries");
    }
    const [key, value] = pair;
    if (typeof key !== "string" || !/^[a-z_]{1,24}$/.test(key)) throw new TypeError("invalid key");
    if (!Number.isSafeInteger(value)) throw new TypeError("invalid value");
    if (seen.has(key)) throw new TypeError("duplicate key");
    seen.add(key);
    rows.push([key, value === 0 ? 0 : value]);
  }
  const result = Object.create(null);
  for (const [key, value] of rows) {
    Object.defineProperty(result, key, {
      value, enumerable: true, writable: false, configurable: false
    });
  }
  return Object.freeze(result);
}
const input = [["pens", 3], ["__proto__", 7], ["constructor", 2]];
const table = makeLookup(input);
console.log(JSON.stringify(Object.entries(table)));
console.log(Object.getPrototypeOf(table) === null, Object.isFrozen(table));
console.log(Reflect.set(table, "pens", 9), table.pens);
console.log(JSON.stringify(input));

// ✅ Expected output:
// [["pens",3],["__proto__",7],["constructor",2]]
// true true
// false 3
// [["pens",3],["__proto__",7],["constructor",2]]

Practice quiz

What does this complete program print? const x = Object.create({ a: 1 }); x.b = 2; console.log(Object.keys(x).join(","));

  • b
  • a,b
  • a
  • b,a

Answer: b. Object.keys includes only own enumerable string keys.

What does this complete program print? const s = Symbol("x"); const x = { [s]: 1 }; console.log(Object.keys(x).length, Reflect.ownKeys(x).length);

  • 1 1
  • 0 1
  • 0 0
  • 1 0

Answer: 0 1. Reflect.ownKeys includes the own symbol; Object.keys does not.

What does this complete program print? const x = Object.fromEntries([["a", 1], ["a", 3]]); console.log(x.a);

  • 1
  • undefined
  • 3
  • TypeError

Answer: 3. A later entry replaces an earlier value for the same key.

What does this complete program print? const a = { n: 1 }; console.log(Object.assign(a, { n: 4 }) === a, a.n);

  • false 4
  • true 1
  • false 1
  • true 4

Answer: true 4. assign mutates and returns its target.

What does this complete program print? const x = Object.freeze({ inner: { n: 1 } }); x.inner.n = 2; console.log(x.inner.n);

  • 2
  • 1
  • undefined
  • TypeError

Answer: 2. Freezing the outer object does not freeze its nested value.

What does this complete program print? const x = Object.seal({ n: 1 }); console.log(Reflect.set(x, "n", 2), Reflect.deleteProperty(x, "n"));

  • false false
  • true false
  • true true
  • false true

Answer: true false. Sealed data properties remain writable unless separately made non-writable; deletion is refused.

What does this complete program print? const x = Object.create(null); x.a = undefined; console.log(Object.hasOwn(x, "a"), Object.hasOwn(x, "b"));

  • false false
  • true true
  • true false
  • false true

Answer: true false. Own presence is independent of an undefined value.

What does this complete program print? const x = { "12": 1, z: 2, "3": 3 }; console.log(Object.keys(x).join(","));

  • 12,z,3
  • z,3,12
  • 12,3,z
  • 3,12,z

Answer: 3,12,z. Array-index keys are ordered numerically before other string keys.

Continue this course

Related lessons