JavaScript Reference: Object

By

Published · Updated

Tagged: JavaScript

Complete reference to the JavaScript Object type, static methods (Object.assign, create, keys, values, entries, freeze, seal, defineProperty, hasOwn, is, groupBy), and Object.prototype methods.

This reference documents how JavaScript objects work along with every built-in Object static method and Object.prototype instance method.

Any value that is not a primitive (string, number, bigint, boolean, symbol, null, or undefined) is an object. Arrays, functions, dates, maps, and regular expressions are all objects under the hood.

Creating objects

The most common way is an object literal:

const person = {
  age: 36,
  name: 'Flavio',
  speak() {
    return `Hi, I'm ${this.name}`
  },
}
typeof person // 'object'

You can also create an object with Object.create(proto) when you want an explicit prototype — pass null for a pure dictionary with no inherited methods:

const dict = Object.create(null)

For how properties, descriptors, and getters/setters work in detail, see JavaScript Object Properties.

Passed by reference

Primitives are copied by value; objects are passed by reference. Assigning an object to another variable points both variables to the same object:

const car = { color: 'blue' }
const anotherCar = car
anotherCar.color = 'yellow'
car.color // 'yellow'

When you need an independent copy, use { ...obj } for a shallow clone or structuredClone(obj) for a deep clone (see how to deep clone a JavaScript object).

Built-in Object properties


Static methods

Copying, creating, and grouping

Object.assign(target, ...sources) (ES2015)

Copies all enumerable own properties from one or more source objects into target and returns target. It performs a shallow copy (nested objects are still shared by reference) and mutates target:

const defaults = { theme: 'light', fontSize: 16 }
const merged = Object.assign({}, defaults, { theme: 'dark' })
// { theme: 'dark', fontSize: 16 }

Object.create(proto, propertiesObject?)

Creates a new object whose prototype is proto, optionally defining properties using property descriptors:

const animal = {
  speak() {
    return `${this.name} makes a sound`
  },
}
const dog = Object.create(animal, {
  name: { value: 'Roger', enumerable: true },
})
dog.speak() // 'Roger makes a sound'

Object.groupBy(items, callbackFn) (ES2024)

Groups elements of any iterable into a null-prototype object keyed by the return value of callbackFn. See the full guide: How to group array items with Object.groupBy().


Inspecting keys, values, and entries

Object.keys(obj)

Returns an array of obj’s own enumerable string-keyed property names:

Object.keys({ name: 'Flavio', age: 43 }) // ['name', 'age']

Object.values(obj) (ES2017)

Returns an array of obj’s own enumerable string-keyed property values:

Object.values({ name: 'Flavio', age: 43 }) // ['Flavio', 43]

Object.entries(obj) (ES2017)

Returns an array of [key, value] pairs for obj’s own enumerable string-keyed properties (useful with for...of, Map, and Object.fromEntries()):

Object.entries({ name: 'Flavio', age: 43 })
// [['name', 'Flavio'], ['age', 43]]

Object.getOwnPropertyNames(obj)

Like Object.keys(), but includes non-enumerable own string properties (still excludes symbols and inherited properties):

Object.getOwnPropertyNames(['a', 'b']) // ['0', '1', 'length']

Object.getOwnPropertySymbols(obj) (ES2015)

Returns an array of all own Symbol properties found directly on obj:

const id = Symbol('id')
const user = { name: 'Flavio', [id]: 123 }
Object.getOwnPropertySymbols(user) // [Symbol(id)]

Object.hasOwn(obj, prop) (ES2022)

Returns true if obj has prop as its own (non-inherited) property. Prefer Object.hasOwn() over obj.hasOwnProperty() because it also works safely on objects created with Object.create(null):

const dict = Object.create(null)
dict.key = 1
Object.hasOwn(dict, 'key') // true

Property descriptors

Object.defineProperty(obj, prop, descriptor)

Adds or modifies a single property on obj with explicit control over value, writable, enumerable, configurable, or get/set:

const user = {}
Object.defineProperty(user, 'id', {
  value: 42,
  writable: false,
  enumerable: true,
  configurable: false,
})

Object.defineProperties(obj, props)

Defines or modifies multiple properties on obj at once:

const user = {}
Object.defineProperties(user, {
  id: { value: 42, enumerable: true },
  role: { value: 'admin', writable: true, enumerable: true },
})

Object.getOwnPropertyDescriptor(obj, prop)

Returns the property descriptor object (value, writable, enumerable, configurable, or get/set) for one own property, or undefined if not found:

Object.getOwnPropertyDescriptor({ a: 1 }, 'a')
// { value: 1, writable: true, enumerable: true, configurable: true }

Object.getOwnPropertyDescriptors(obj) (ES2017)

Returns an object mapping every own property (string and symbol) to its descriptor. Commonly paired with Object.create() to make a shallow copy that preserves getters, setters, and non-writable flags:

const copy = Object.create(
  Object.getPrototypeOf(original),
  Object.getOwnPropertyDescriptors(original),
)

Preventing mutations (freeze, seal, extensibility)

All three mutability locks mutate the object in place, return the same object, and are shallow (nested objects remain mutable unless locked too).

Object.preventExtensions(obj) & Object.isExtensible(obj)

Object.preventExtensions(obj) stops new properties from being added while still allowing edits and deletions of existing properties. Object.isExtensible(obj) checks whether new properties can still be added:

const dog = { name: 'Roger' }
Object.isExtensible(dog) // true
Object.preventExtensions(dog)
Object.isExtensible(dog) // false

Object.seal(obj) & Object.isSealed(obj)

Object.seal(obj) prevents adding or deleting properties (marks all properties non-configurable), while still allowing you to change values of existing writable properties:

const dog = Object.seal({ name: 'Roger' })
dog.name = 'Syd' // allowed
delete dog.name // false (throws in strict mode)
Object.isSealed(dog) // true

Object.freeze(obj) & Object.isFrozen(obj)

Object.freeze(obj) is the strictest lock: no adding, deleting, or modifying own properties. In strict mode, attempts to mutate throw a TypeError:

const config = Object.freeze({ port: 3000 })
Object.isFrozen(config) // true

Prototypes and equality

Object.getPrototypeOf(obj)

Returns the prototype ([[Prototype]]) of obj:

Object.getPrototypeOf([]) === Array.prototype // true
Object.getPrototypeOf(Object.create(null)) // null

Object.setPrototypeOf(obj, proto) (ES2015)

Changes the prototype of an existing object. Avoid in hot paths because mutating prototypes de-optimizes property lookups in JS engines — prefer Object.create(proto) when creating new objects instead.

Object.is(value1, value2) (ES2015)

Compares two values using SameValue equality — identical to === except that NaN equals NaN, and +0 does not equal -0:

Object.is(NaN, NaN) // true (NaN === NaN is false)
Object.is(+0, -0) // false (+0 === -0 is true)
Object.is('a', 'a') // true

Instance methods (Object.prototype)

Every normal object inherits these methods from Object.prototype (objects created with Object.create(null) do not).

obj.hasOwnProperty(prop)

Returns true if prop is an own property (not inherited). Prefer Object.hasOwn(obj, prop) in modern code so null-prototype objects and shadowed hasOwnProperty keys cannot break it.

proto.isPrototypeOf(obj)

Returns true if proto appears anywhere in obj’s prototype chain:

Array.prototype.isPrototypeOf([]) // true
Object.prototype.isPrototypeOf([]) // true

obj.propertyIsEnumerable(prop)

Returns true if prop is an own property of obj and its enumerable descriptor flag is true:

;({ a: 1 }).propertyIsEnumerable('a') // true
;[].propertyIsEnumerable('length') // false

obj.toString()

Returns a string representation of the object (default '[object Object]'). Built-in types and custom classes override it; calling Object.prototype.toString.call(val) is a classic way to inspect internal tags ('[object Date]', '[object Map]').

obj.toLocaleString()

Calls toString() by default on plain objects, and is overridden by Date, Number, and Array to produce locale-aware formatting.

obj.valueOf()

Returns the object itself by default (obj.valueOf() === obj). JavaScript calls it when coercing an object to a primitive value; custom classes can override it to participate in numeric comparisons.

Want me to talk about your product? You can sponsor this site.

Related posts about js: