JavaScript Object Methods Cheat Sheet
Quick-reference for Object static methods and object literal features. Each section includes copy-ready snippets with inline output comments.
Object.keys(), values(), entries()
Extract keys, values, or key-value pairs as arrays. Only includes own enumerable string-keyed properties.
const user = { name: 'Alice', age: 30, role: 'admin' };
Object.keys(user) // => ['name', 'age', 'role']const user = { name: 'Alice', age: 30, role: 'admin' };
Object.values(user) // => ['Alice', 30, 'admin']const user = { name: 'Alice', age: 30 };
Object.entries(user)
// => [['name', 'Alice'], ['age', 30]]
// Useful with for...of
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}const prices = { apple: 1.5, banana: 0.8, cherry: 2.0 };
const doubled = Object.fromEntries(
Object.entries(prices).map(([k, v]) => [k, v * 2])
);
// => { apple: 3, banana: 1.6, cherry: 4 }Object.assign() vs Spread
Both merge objects. Spread is cleaner syntax; assign mutates the target. Both do shallow copies only.
const target = { a: 1 };
Object.assign(target, { b: 2 }, { c: 3 });
target // => { a: 1, b: 2, c: 3 } (mutated!)const merged = { ...obj1, ...obj2 };
// obj1 and obj2 are unchanged
const updated = { ...user, name: 'Bob' };
// Override specific propertiesconst original = { a: 1, nested: { b: 2 } };
const copy = { ...original };
copy.nested.b = 99;
original.nested.b // => 99 (shared reference!)
// Deep copy: use structuredClone
const deep = structuredClone(original);Both spread and Object.assign only copy the first level. Nested objects are still shared references.
// React state update pattern
setState(prev => ({
...prev,
count: prev.count + 1,
}));Object.freeze() and Object.seal()
Prevent modifications to objects. freeze is read-only; seal allows value changes but no structural changes.
const config = Object.freeze({ port: 3000, host: 'localhost' });
config.port = 8080; // silently ignored (strict mode: TypeError)
config.port // => 3000 (unchanged)
config.newProp = true; // silently ignoredconst user = Object.seal({ name: 'Alice', age: 30 });
user.age = 31; // OK: existing property can change
user.email = 'a@b.com'; // silently ignored (no new props)
delete user.name; // silently ignored (no deletions)Object.isFrozen(config) // => true
Object.isSealed(user) // => trueconst obj = Object.freeze({ nested: { value: 1 } });
obj.nested.value = 2;
obj.nested.value // => 2 (nested object NOT frozen)
// Deep freeze requires recursion
function deepFreeze(obj) {
Object.freeze(obj);
Object.values(obj).forEach(v => {
if (typeof v === 'object' && v !== null) deepFreeze(v);
});
return obj;
}Object.fromEntries()
Convert an iterable of [key, value] pairs into an object. The inverse of Object.entries().
Object.fromEntries([['name', 'Alice'], ['age', 30]])
// => { name: 'Alice', age: 30 }const map = new Map([['a', 1], ['b', 2]]);
Object.fromEntries(map) // => { a: 1, b: 2 }const prices = { apple: 1.5, banana: 0.8 };
const formatted = Object.fromEntries(
Object.entries(prices).map(([k, v]) => [k, `$${v.toFixed(2)}`])
);
// => { apple: '$1.50', banana: '$0.80' }const data = { name: 'Alice', password: 'secret', role: 'admin' };
const safe = Object.fromEntries(
Object.entries(data).filter(([key]) => key !== 'password')
);
// => { name: 'Alice', role: 'admin' }Object.create()
Create an object with a specific prototype. Useful for prototype chain manipulation and null-prototype objects.
const animal = {
speak() { return `${this.name} makes a sound`; }
};
const dog = Object.create(animal);
dog.name = 'Rex';
dog.speak() // => 'Rex makes a sound'const dict = Object.create(null);
dict.key = 'value';
dict.toString // => undefined (no Object.prototype methods)
// Useful for lookup tables without prototype pollution
dict.constructor // => undefined (truly clean)Object.create(null) creates an object with no prototype chain — no hasOwnProperty, no toString. Use for safe lookup maps.
// Object.create is low-level prototype wiring
// Classes are the modern, preferred approach for inheritance
class Animal {
speak() { return `${this.name} speaks`; }
}
class Dog extends Animal {
constructor(name) { super(); this.name = name; }
}Property Checking: hasOwn, in, hasOwnProperty
Check whether an object has a property. Object.hasOwn() is the modern, safe approach.
const user = { name: 'Alice', age: 30 };
Object.hasOwn(user, 'name') // => true
Object.hasOwn(user, 'toString') // => false (inherited)const user = { name: 'Alice' };
'name' in user // => true
'toString' in user // => true (inherited from Object.prototype)const user = { name: 'Alice' };
user.hasOwnProperty('name') // => true
user.hasOwnProperty('toString') // => false
// Can break with Object.create(null):
const dict = Object.create(null);
// dict.hasOwnProperty('key') // TypeError!
Object.hasOwn(dict, 'key') // => false (always safe)Prefer Object.hasOwn() over hasOwnProperty(). It works with Object.create(null) objects and is more concise.
Computed Properties and Shorthand
ES6 shorthand for property names, methods, and dynamic keys.
const name = 'Alice';
const age = 30;
const user = { name, age };
// Equivalent to: { name: name, age: age }const obj = {
greet() { return 'hello'; }, // shorthand
// greet: function() { return 'hello'; } // equivalent
};const field = 'email';
const user = {
[field]: 'alice@example.com', // => { email: 'alice@example.com' }
[`${field}Verified`]: true, // => { emailVerified: true }
};function setProp(obj, key, value) {
return { ...obj, [key]: value };
}
setProp({}, 'name', 'Alice') // => { name: 'Alice' }Getters and Setters
Define computed properties with get/set syntax. Accessed like regular properties but run a function behind the scenes.
const user = {
firstName: 'Alice',
lastName: 'Smith',
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
};
user.fullName // => 'Alice Smith' (accessed like a property)const account = {
_balance: 0,
get balance() { return this._balance; },
set balance(value) {
if (value < 0) throw new Error('Negative balance');
this._balance = value;
},
};
account.balance = 100; // OK
// account.balance = -1; // Error: Negative balanceclass Circle {
constructor(radius) { this.radius = radius; }
get area() { return Math.PI * this.radius ** 2; }
get diameter() { return this.radius * 2; }
}
const c = new Circle(5);
c.area // => 78.54...
c.diameter // => 10Optional Chaining on Objects
Safely access deeply nested properties without checking each level for null/undefined.
const user = { profile: { address: { city: 'NYC' } } };
user?.profile?.address?.city // => 'NYC'
user?.settings?.theme // => undefined (no error)const obj = { greet() { return 'hello'; } };
obj?.greet?.() // => 'hello'
obj?.missing?.() // => undefined (no TypeError)const theme = config?.ui?.theme ?? 'light';
const port = config?.server?.port ?? 3000;
const timeout = options?.retry?.timeout ?? 5000;delete user?.profile?.avatar;
// Safe: no error if user or profile is null/undefinedDestructuring Patterns
Extract object properties into variables. Supports renaming, defaults, nesting, and rest.
function createUser({ name, role = 'user', email }) {
return { name, role, email };
}
createUser({ name: 'Alice', email: 'a@b.com' });
// => { name: 'Alice', role: 'user', email: 'a@b.com' }const { password, ...safeUser } = {
name: 'Alice',
password: 'secret',
role: 'admin',
};
safeUser // => { name: 'Alice', role: 'admin' }const { name: userName, age: userAge } = { name: 'Alice', age: 30 };
userName // => 'Alice'
userAge // => 30const {
db: { host, port = 5432 },
auth: { secret },
} = config;Deep destructuring can be hard to read. Consider destructuring one level at a time for clarity.