typescript
Object Properties and Methods in JavaScript and TypeScript - Interview Question
These come up in interviews constantly. Here's a quick reference for the Object methods you'll actually use — and what each one does.
15 Apr 2024

These come up in interviews constantly. Here's a quick reference for the Object methods you'll actually use — and what each one does.
Reading an object
Object.keys() — returns an array of the object's own property names.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj)); // ["a", "b", "c"]
Object.values() — returns an array of the object's own property values.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj)); // [1, 2, 3]
Object.entries() — returns an array of [key, value] pairs. Useful when you need both.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj)); // [["a", 1], ["b", 2], ["c", 3]]
Combining and creating objects
Object.assign() — copies properties from source objects to a target. Mutates the target.
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
const merged = Object.assign(target, source);
console.log(merged); // { a: 1, b: 3, c: 4 }
Watch out: this is a shallow copy. Nested objects are still references. For deep copies, use structuredClone().
Object.create() — creates a new object with a specific prototype.
const person = {
greet() {
console.log('Hello!');
}
};
const john = Object.create(person);
john.greet(); // Hello!
Protecting objects
Object.freeze() — prevents adding, removing, or changing properties. Shallow only.
const obj = { a: 1, b: 2 };
Object.freeze(obj);
obj.c = 3; // silently ignored (or throws in strict mode)
console.log(obj); // { a: 1, b: 2 }
hasOwnProperty() — checks if a property belongs directly to the object, not its prototype chain.
const obj = { a: 1, b: 2 };
console.log(obj.hasOwnProperty('a')); // true
console.log(obj.hasOwnProperty('toString')); // false

The pattern I see in interviews
Interviewers ask about these to gauge whether you understand objects beyond dot notation. Know the difference between own and inherited properties. Know that Object.assign mutates. Know that Object.freeze is shallow. These details separate a confident answer from a shaky one.