Objects in JavaScript
Objects are key/value maps and the fundamental building block for structured data.
Creating objects
const o1 = { a: 1, b: 2 }
const o2 = Object.create(null) // no prototype
Property access
Dot vs bracket notation; computed keys.
o1.a
const k = 'b'
o1[k]
const key = `x_${Date.now()}`
const obj = { [key]: 42 }
Shorthand and methods
const a = 1
const user = {
a, // shorthand property
greet(name) { return `Hi ${name}` }, // method shorthand
}
Descriptors and immutability
Control writability, enumerability, and configurability.
Object.defineProperty(o1, 'hidden', { value: 1, writable: false })
Object.freeze(o1) // shallow immutable
Object.seal(o1) // no add/remove
Prototype and __proto__
Every object (except Object.create(null)) has a prototype. Prefer Object.getPrototypeOf/setPrototypeOf.
const p = { z: 9 }
const c = Object.create(p)
Copy and merge
const copy = { ...o1 }
const merged = { ...o1, ...{ c: 3 } }
Object.assign({}, o1, { c: 3 })
JSON
Serialize/deserialize data structures.
const txt = JSON.stringify({ a: 1 })
const back = JSON.parse(txt)
hasOwn and iteration
Object.hasOwn(o1, 'a') // ES2022
for (const k of Object.keys(o1)) {}
for (const [k,v] of Object.entries(o1)) {}
Summary
- Use literals and shorthand; compute keys with brackets
- Control mutability with descriptors/freeze; use spread/assign to copy/merge
- Prefer
Object.hasOwn/Object.keysfor safe iteration