Skip to content
Velloreth
Programming 8 min read

JavaScript Object Methods: A Practical Reference

Object.keys, entries, assign, freeze and the rest. Learn what each does, the shallow-copy trap, and the modern alternatives.

By

Converting to arrays

Object.keys

Returns an array of the object’s own enumerable keys.

const user = { name: 'Ada', age: 36 };
Object.keys(user); // ['name', 'age']

Object.values

Returns the values.

Object.values(user); // ['Ada', 36]

Object.entries

Returns [key, value] pairs.

Object.entries(user);
// [['name', 'Ada'], ['age', 36]]

These three are the bridge between objects and array methods.

// Sum all values
const total = Object.values(prices).reduce((a, b) => a + b, 0);

// Filter an object by value
const active = Object.fromEntries(
  Object.entries(users).filter(([, u]) => u.active),
);

Object.fromEntries

The inverse of entries, building an object from pairs.

Object.fromEntries([['a', 1], ['b', 2]]);
// { a: 1, b: 2 }

This makes the transform-filter-rebuild pattern clean.

Iterating

// Keys
for (const key of Object.keys(obj)) { }

// Values
for (const value of Object.values(obj)) { }

// Entries, with destructuring
for (const [key, value] of Object.entries(obj)) { }

// for...in also walks the prototype chain
for (const key in obj) {
  if (Object.hasOwn(obj, key)) { } // guard needed
}

for...in includes inherited enumerable properties, which is why it usually needs a guard. Object.entries with for...of avoids the problem entirely and is the modern preference.

Copying

Shallow copy

const copy = { ...original };
const copy2 = Object.assign({}, original);

Both copy the top-level properties. Nested objects are shared.

const original = { user: { name: 'Ada' } };
const copy = { ...original };

copy.user.name = 'Grace';
console.log(original.user.name); // 'Grace' — the nested object is shared

This is the most common source of bugs with object copying. The spread looks like a copy, but it is one level deep.

Deep copy

const deep = structuredClone(original);

structuredClone handles nested objects, arrays, Date, Map, Set, and circular references. It does not handle functions, DOM nodes, or class prototypes.

The older trick:

const deep = JSON.parse(JSON.stringify(original));

This works only for JSON-safe values. It loses Date objects (converting them to strings), undefined, functions, Map, Set, and it throws on circular references. structuredClone is the modern replacement.

Merging

const merged = { ...defaults, ...overrides };

Later properties win. This is the standard way to apply defaults.

const config = { ...defaultConfig, ...userConfig };

Note that the merge is shallow, so a nested object in userConfig replaces the whole nested object in defaultConfig rather than merging into it.

Property checks

Object.hasOwn

The safe own-property check.

Object.hasOwn(user, 'name'); // true
Object.hasOwn(user, 'toString'); // false — inherited

The older user.hasOwnProperty('name') works but can fail if the object has a property named hasOwnProperty, or if it was created with Object.create(null).

The in operator

Checks the object and its prototype chain.

'name' in user;      // true
'toString' in user;  // true — inherited from Object.prototype

Use in when you want to include inherited properties, and Object.hasOwn when you do not.

Checking for undefined

// Wrong: fails if the property exists with value undefined
if (user.name !== undefined) { }

// Right: checks existence
if (Object.hasOwn(user, 'name')) { }

The distinction matters when a property can legitimately be undefined.

Freezing and sealing

Object.freeze

Prevents adding, removing, or reassigning properties.

const config = Object.freeze({ apiUrl: 'https://api.example.com' });
config.apiUrl = 'other'; // silently fails (or throws in strict mode)

It is shallow. Nested objects remain mutable.

const config = Object.freeze({ db: { host: 'localhost' } });
config.db.host = 'remote'; // works — the nested object is not frozen

A deep freeze requires walking the object:

function deepFreeze(obj) {
  for (const value of Object.values(obj)) {
    if (value && typeof value === 'object') deepFreeze(value);
  }
  return Object.freeze(obj);
}

Object.seal

Prevents adding or removing properties, but allows reassigning existing ones.

const obj = Object.seal({ a: 1 });
obj.a = 2;   // works
obj.b = 3;   // fails — cannot add

Object.isFrozen and Object.isSealed

Object.isFrozen(config); // true
Object.isSealed(config); // false

Describing properties

Object.getOwnPropertyDescriptor

const desc = Object.getOwnPropertyDescriptor(obj, 'name');
// { value: 'Ada', writable: true, enumerable: true, configurable: true }

Object.defineProperty

Lets you control the property’s behaviour.

Object.defineProperty(obj, 'id', {
  value: 42,
  writable: false,
  enumerable: false,
  configurable: false,
});

Non-enumerable properties are skipped by Object.keys, JSON.stringify, and spread. This is how built-in methods like toString are hidden from iteration.

Getters and setters

const obj = {
  _value: 0,
  get value() { return this._value; },
  set value(v) { this._value = Math.max(0, v); },
};

A getter runs on every access, which matters for performance if it does real work.

Prototypes

Object.create

Creates an object with a specified prototype.

const proto = { greet() { return 'hi'; } };
const obj = Object.create(proto);
obj.greet(); // 'hi'

Object.create(null) creates an object with no prototype, which is useful as a dictionary because it has no inherited keys.

const dict = Object.create(null);
dict.toString = 'value'; // no conflict with Object.prototype.toString

Object.getPrototypeOf

Object.getPrototypeOf(obj) === proto; // true

Property order

Object property order is mostly insertion order, with one exception: integer-like keys come first, in ascending numeric order.

const obj = { b: 1, 2: 'two', a: 2, 1: 'one' };
Object.keys(obj); // ['1', '2', 'b', 'a']

The integer-like keys are sorted numerically and placed first, then the string keys in insertion order. This matters when you rely on order for display, and it is a reason to use a Map when order is significant.

A key is “integer-like” if it is a canonical numeric string. '1' qualifies; '01' and '1.5' do not.

Serialisation

JSON.stringify uses the object’s own enumerable properties.

const user = { name: 'Ada', age: 36 };
JSON.stringify(user); // '{"name":"Ada","age":36}'

What is lost:

  • Functions are omitted.
  • undefined values are omitted.
  • Symbols are omitted.
  • Non-enumerable properties are omitted.
  • Date objects become ISO strings.
  • Map and Set become {}.
  • Circular references throw.
JSON.stringify({ a: undefined, b: () => {}, c: 1 }); // '{"c":1}'

The replacer argument controls what is included.

JSON.stringify(user, ['name']); // only the name
JSON.stringify(user, (key, value) => (key === 'password' ? undefined : value));

The second form is the standard way to strip sensitive fields before logging or sending.

Objects as maps

Using a plain object as a dictionary works, but it has sharp edges worth knowing.

Prototype pollution. Every object inherits from Object.prototype, so a key like toString or constructor collides with an inherited property. Reading obj.toString returns a function rather than undefined, which breaks existence checks.

const dict = {};
dict['toString']; // [Function: toString] — not undefined

The fixes are Object.create(null), which has no prototype, or a Map, which has no inherited keys at all.

Key coercion. All keys become strings, so obj[1] and obj['1'] are the same key. A Map preserves the original type.

No size. Object.keys(obj).length allocates an array to count. A Map has a size property.

Order. Integer-like keys are sorted first, which can surprise when order matters.

For a fixed-shape record with known fields, a plain object is the right choice. For a dynamic dictionary, a Map is usually better.

A note on immutability

Object methods are the toolkit for treating objects as immutable values. The spread operator and Object.assign both produce a new object rather than changing the original, which is what makes state updates predictable. The discipline is to never mutate an object that something else holds a reference to, and to build a new one instead. This costs an allocation, but it removes a whole class of bugs where a change in one place is visible somewhere unexpected. The exception is a large object in a hot path, where the allocation matters and mutation is contained to a single owner.

Practical guidance

  • Use Object.entries to iterate an object with array methods.
  • Use Object.fromEntries to rebuild an object after transforming.
  • Remember spread is a shallow copy — nested objects are shared.
  • Use structuredClone for a deep copy.
  • Use Object.hasOwn for own-property checks.
  • Remember Object.freeze is shallow.
  • Use Object.create(null) for dictionaries.
  • Prefer for...of over for...in to avoid prototype-chain surprises.

For the related guides, see javascript-array-methods-guide and javascript-destructuring-guide. For the broader context, immutability-explained and json-vs-yaml-vs-toml.

Quotable summary

Object.keys, values, and entries convert an object into an array, which lets you use array methods on it, and Object.fromEntries rebuilds an object from pairs. Object.assign and the spread operator both perform a shallow copy, so nested objects are still shared, which is the most common source of copying bugs. Object.freeze is shallow too, so a frozen object’s nested objects remain mutable, and a deep freeze requires walking the object. Use Object.hasOwn instead of hasOwnProperty for a safe own-property check, and use structuredClone for a deep copy rather than the JSON round-trip, which loses dates, undefined, and functions. Prefer for…of over for…in, because for…in walks the prototype chain and usually needs a guard.

Frequently asked questions

What is the difference between Object.keys and Object.getOwnPropertyNames?
Object.keys returns only enumerable string-keyed properties. getOwnPropertyNames includes non-enumerable ones. For most objects they are the same, but they differ for built-in objects and class instances.
How do I deep-copy an object in JavaScript?
Use structuredClone, which handles nested objects, arrays, dates, maps, and sets. The JSON.parse(JSON.stringify(obj)) trick works only for JSON-safe values and loses dates, undefined, and functions.
Is Object.freeze a deep freeze?
No. It prevents adding, removing, or reassigning top-level properties, but nested objects remain mutable. A deep freeze requires walking the object and freezing each level.
What is the difference between Object.assign and spread?
Both copy enumerable own properties into a target. Spread is syntax and creates a new object; Object.assign can mutate an existing target. Spread is usually preferred for readability.
How do I check if an object has a property?
Use Object.hasOwn(obj, 'key') for an own-property check. The in operator also checks the prototype chain. Avoid obj.hasOwnProperty directly, because an object can shadow it.
What does Object.entries return?
An array of [key, value] pairs, which you can iterate with for...of or destructure in a map. It is the standard way to iterate an object's own enumerable properties.