Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. JavaScript
  4. JavaScript Object Methods Cheat Sheet
JavaScriptCheat Sheet

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.

On this page
  1. 1Object.keys(), values(), entries()
  2. 2Object.assign() vs Spread
  3. 3Object.freeze() and Object.seal()
  4. 4Object.fromEntries()
  5. 5Object.create()
  6. 6Property Checking: hasOwn, in, hasOwnProperty
  7. 7Computed Properties and Shorthand
  8. 8Getters and Setters
  9. 9Optional Chaining on Objects
  10. 10Destructuring Patterns
Object.keys(), values(), entries()Object.assign() vs SpreadObject.freeze() and Object.seal()Object.fromEntries()Object.create()Property Checking: hasOwn, in, hasOwnPropertyComputed Properties and ShorthandGetters and SettersOptional Chaining on ObjectsDestructuring Patterns

Object.keys(), values(), entries()

Extract keys, values, or key-value pairs as arrays. Only includes own enumerable string-keyed properties.

Object.keys()
const user = { name: 'Alice', age: 30, role: 'admin' };
Object.keys(user)    // => ['name', 'age', 'role']
Object.values()
const user = { name: 'Alice', age: 30, role: 'admin' };
Object.values(user)  // => ['Alice', 30, 'admin']
Object.entries()
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}`);
}
Iterate and transform
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.

Object.assign() — mutates target
const target = { a: 1 };
Object.assign(target, { b: 2 }, { c: 3 });
target  // => { a: 1, b: 2, c: 3 } (mutated!)
Spread — creates new object
const merged = { ...obj1, ...obj2 };
// obj1 and obj2 are unchanged

const updated = { ...user, name: 'Bob' };
// Override specific properties
Shallow copy (both methods)
const 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.

Prefer spread for immutable patterns
// 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.

Object.freeze() — fully immutable (shallow)
const config = Object.freeze({ port: 3000, host: 'localhost' });
config.port = 8080;    // silently ignored (strict mode: TypeError)
config.port            // => 3000 (unchanged)
config.newProp = true; // silently ignored
Object.seal() — no add/delete, values writable
const 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)
Check frozen/sealed state
Object.isFrozen(config)  // => true
Object.isSealed(user)    // => true
Freeze is shallow
const 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().

From entries array
Object.fromEntries([['name', 'Alice'], ['age', 30]])
// => { name: 'Alice', age: 30 }
From Map
const map = new Map([['a', 1], ['b', 2]]);
Object.fromEntries(map)  // => { a: 1, b: 2 }
Transform object values
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' }
Filter object properties
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.

Create with prototype
const animal = {
  speak() { return `${this.name} makes a sound`; }
};

const dog = Object.create(animal);
dog.name = 'Rex';
dog.speak()  // => 'Rex makes a sound'
Null prototype — pure dictionary
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.

vs class inheritance
// 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.

Object.hasOwn() — recommended (ES2022)
const user = { name: 'Alice', age: 30 };
Object.hasOwn(user, 'name')      // => true
Object.hasOwn(user, 'toString')  // => false (inherited)
in operator — checks own + inherited
const user = { name: 'Alice' };
'name' in user       // => true
'toString' in user   // => true (inherited from Object.prototype)
hasOwnProperty() — legacy approach
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.

Shorthand properties
const name = 'Alice';
const age = 30;
const user = { name, age };
// Equivalent to: { name: name, age: age }
Shorthand methods
const obj = {
  greet() { return 'hello'; },      // shorthand
  // greet: function() { return 'hello'; }  // equivalent
};
Computed property names
const field = 'email';
const user = {
  [field]: 'alice@example.com',        // => { email: 'alice@example.com' }
  [`${field}Verified`]: true,           // => { emailVerified: true }
};
Dynamic key from variable
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.

Getter on object literal
const user = {
  firstName: 'Alice',
  lastName: 'Smith',
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
};
user.fullName  // => 'Alice Smith' (accessed like a property)
Setter with validation
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 balance
In classes
class 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  // => 10

Optional Chaining on Objects

Safely access deeply nested properties without checking each level for null/undefined.

Nested property access
const user = { profile: { address: { city: 'NYC' } } };
user?.profile?.address?.city  // => 'NYC'
user?.settings?.theme         // => undefined (no error)
Method calls
const obj = { greet() { return 'hello'; } };
obj?.greet?.()      // => 'hello'
obj?.missing?.()    // => undefined (no TypeError)
With nullish coalescing
const theme = config?.ui?.theme ?? 'light';
const port = config?.server?.port ?? 3000;
const timeout = options?.retry?.timeout ?? 5000;
delete with optional chaining
delete user?.profile?.avatar;
// Safe: no error if user or profile is null/undefined

Destructuring Patterns

Extract object properties into variables. Supports renaming, defaults, nesting, and rest.

Function parameter destructuring
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' }
Rest in destructuring
const { password, ...safeUser } = {
  name: 'Alice',
  password: 'secret',
  role: 'admin',
};
safeUser  // => { name: 'Alice', role: 'admin' }
Rename during destructuring
const { name: userName, age: userAge } = { name: 'Alice', age: 30 };
userName  // => 'Alice'
userAge   // => 30
Nested destructuring
const {
  db: { host, port = 5432 },
  auth: { secret },
} = config;

Deep destructuring can be hard to read. Consider destructuring one level at a time for clarity.

Learn JavaScript in Depth
JavaScript Collections Practice →JavaScript Functions Practice →
See Also
Array Methods →ES6+ Features →

Start Practicing JavaScript

Free daily exercises with spaced repetition. No credit card required.

← Back to JavaScript Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.