JavaScript Object

Object key order, inherited properties, Object.hasOwn, and Object.assign, compared with Map.

Ordinary objects are ECMAScript built-ins. Their keys are strings or symbols. If you need keys that are numbers, objects, or NaN, use Map.

An object has a prototype chain. A property can be inherited, which affects the in operator and some enumeration pitfalls.

Examples were checked in Node.js 22, which implements these ECMAScript built-ins. See the MDN documentation for the complete API.

JavaScript tutorial and API overview →

API index

APISummary
Object.keysReturn an array of the object’s own enumerable string keys, in the order described above.
Object.hasOwn and Object.assignTest whether a property is own, and copy own enumerable properties onto a target object.

Property order

For ordinary string keys, Object.keys() and similar methods visit integer-index keys first, in ascending numeric order, and then the remaining string keys in insertion order. That is why 10 is listed before b, even if 10 was added later.

This order is useful to know when you serialize an object as text. It is not the same as Map iteration, which is insertion order for every key.

Object.keys

Object.keys(object)

Return an array of the object’s own enumerable string keys, in the order described above.

Returns: An array of strings. Symbol keys are omitted. Inherited keys are omitted.

javascript
const o = { b: 1, "2": "two", a: 2, "10": "ten", "1": "one" };
console.log(Object.keys(o).join(","));

Expected output

1,2,10,b,a

Related: Map

MDN documentation →

Prototypes, hasOwn, and assign

The in operator is true for inherited properties. Object.hasOwn() is true only for own properties. Object.assign() copies own enumerable properties and does not copy inherited ones.

Object.hasOwn and Object.assign

Object.hasOwn(object, property)
Object.assign(target, ...sources)

Test whether a property is own, and copy own enumerable properties onto a target object.

ParameterDescription
propertyThe property name or symbol to test with Object.hasOwn().
sourcesOne or more source objects whose own enumerable properties are copied in order.

Returns: Object.hasOwn() returns a boolean. Object.assign() returns the target object.

  • Object.hasOwn() is the current built-in replacement for Object.prototype.hasOwnProperty.call().
  • A for…in loop also visits inherited enumerable properties unless you filter them.
javascript
const proto = { inherited: 1 };
const child = Object.create(proto);
child.own = 2;
console.log(Object.keys(child).join(","));
console.log("inherited" in child, Object.hasOwn(child, "inherited"), Object.hasOwn(child, "own"));
const assigned = Object.assign({}, child);
console.log(Object.keys(assigned).join(","), Object.hasOwn(assigned, "inherited"));

Expected output

own
true false true
own false

MDN documentation →