JavaScript Objects Interview Questions and Answers

Explain object properties, access patterns, descriptors, and the built-in operations used to inspect objects.

Frequently Asked Questions

Important questions are highlighted in the sections below; select one to jump to its answer.

Theoretical JavaScript Interview Questions

The for...in loop walks through the enumerable property names (keys) of an object. It's designed for objects, not arrays. Write for (const key in myObject) and you get each property name as a string, then access values with myObject[key] Read more . Heads up: for...in also iterates over inherited prototype properties, so always use hasOwnProperty() to filter, or better yet, use Object.keys() with forEach for cleaner object iteration.

Almost always use string literals - 'hello' or "hello". They're primitives, fast, and work exactly as you'd expect with ===. String objects (new String('hello')) are wrapper objects and behave oddly - two different new String('hello') instances won't be equal with === because they're different object references. There's virtually no reason to use new String() in real code.

Primitives (strings, numbers, booleans, null, undefined, Symbol, BigInt) are stored by value and are immutable - when you copy one you get a completely independent value. Objects (including arrays and functions) are stored by reference - the variable just holds a pointer to the data in the heap. This is why const with objects doesn't prevent mutation: you can change the object's contents, you just can't reassign the variable to point to a different object.

An object is a collection of key-value pairs where keys are strings or Symbols and values can be anything - primitives, arrays, functions, or other objects. When the value is a function, we call it a method. In JavaScript, almost everything is an object under the hood, so understanding objects well is fundamental to understanding the entire language.

Use an object literal ({}) for one-off data structures - it's simple and clear. Use a constructor function or class with new when you need to create multiple instances that share behavior through the prototype. The literal approach is also slightly faster since the engine doesn't need to set up a prototype chain. In modern code, prefer class syntax over raw constructor functions when you need instances.

Use dot notation (obj.name) for static, known property names - it reads cleanly. Use bracket notation (obj[key]) when the property name is dynamic, stored in a variable, has special characters, or starts with a number. A common real-world use is when processing API responses where you loop over dynamic keys: Object.keys(obj).forEach(key => obj[key]).

Object.keys() gives you an array of property names, Object.values() gives you the values, and Object.entries() gives you [key, value] pairs - all for own enumerable properties only. In practice, entries() is the most powerful because you can destructure it in loops: for (const [key, val] of Object.entries(obj)). It's also the bridge to convert an object into a Map: new Map(Object.entries(obj)).

Object.freeze() makes the object fully read-only at the top level - no adding, removing, or updating properties. Object.seal() locks the shape of the object (no adding or removing) but still lets you update existing property values. The key caveat for both: they're shallow - nested objects are not frozen or sealed, so you need to recursively apply them for deep immutability.

Inside Proxy traps, using Reflect to perform the default operation is considered good practice because it correctly handles edge cases (like receiver context) that doing it manually might get wrong. Also, Reflect.ownKeys() is more complete than Object.keys() because it includes non-enumerable and Symbol keys in one call.

javascript

// Inside a get trap, prefer this:
get(target, key, receiver) {
  return Reflect.get(target, key, receiver); // handles prototype correctly
}

// over this:
get(target, key) {
  return target[key]; // misses the receiver context
}

A property associates a key with a value and may have descriptors controlling writability and enumerability. Keys are strings or symbols; other key values are converted to strings.

Object.keys returns an array of own enumerable string-keyed property names. It excludes symbol keys and inherited properties.

If an object lacks an own property, lookup continues through its prototype until a match is found or the chain ends at null. This supports inheritance without copying properties onto each object.

A descriptor defines attributes such as value and writable for data properties, or get and set for accessors. Object.defineProperty configures them; omitted flags default to false for a new property.

An own property is stored directly on an object; an inherited property is found on a prototype. Object.hasOwn(obj, key) checks ownership without relying on a possibly shadowed method.

Object.freeze prevents extensions and makes own data properties non-writable and non-configurable. It is shallow, so nested objects are not frozen automatically.

JavaScript Practical and Coding Interview Questions

Problem: Write sumValues(record) to add its own enumerable finite numeric values, treating other values as zero. Demonstrate it with a mixed-value object.

javascript

function sumValues(record) {
  return Object.keys(record).reduce(function (sum, key) {
    const value = record[key];
    return sum + (typeof value === 'number' && Number.isFinite(value) ? value : 0);
  }, 0);
}
console.log(sumValues({ apples: 3, pears: 4, note: 'fresh' }));

Problem: Write a recursive clone for values made only of primitives, arrays, and plain objects. Do not use JSON stringify/parse or structuredClone, and do not modify the input.

javascript

function deepClone(value) {
  if (Array.isArray(value)) return value.map(deepClone);
  if (value !== null && typeof value === 'object') {
    return Object.fromEntries(
      Object.entries(value).map(([key, child]) => [key, deepClone(child)])
    );
  }
  return value;
}

const menu = { name: 'tea', steps: ['heat water', { minutes: 4 }] };
const copiedMenu = deepClone(menu);
copiedMenu.steps[1].minutes = 6;
console.log(menu.steps[1].minutes, copiedMenu.steps[1].minutes);

Problem: Merge two JSON-like settings objects. Recursively combine plain objects, replace arrays with copies, and leave both inputs unchanged.

javascript

function isPlainObject(value) {
  return value !== null && typeof value === 'object' &&
    !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
}

function copyValue(value) {
  if (Array.isArray(value)) return value.map(copyValue);
  if (isPlainObject(value)) return mergeDeep({}, value);
  return value;
}

function mergeDeep(base, override) {
  const result = Object.create(null);
  for (const [key, value] of Object.entries(base)) {
    Object.defineProperty(result, key, {
      value: copyValue(value), enumerable: true, writable: true, configurable: true
    });
  }
  for (const [key, value] of Object.entries(override)) {
    const oldValue = base[key];
    const merged = isPlainObject(oldValue) && isPlainObject(value)
      ? mergeDeep(oldValue, value)
      : copyValue(value);
    Object.defineProperty(result, key, {
      value: merged, enumerable: true, writable: true, configurable: true
    });
  }
  return result;
}

const defaults = { editor: { theme: 'light', fontSize: 14 }, tabs: ['home'] };
const preferences = { editor: { fontSize: 18 }, tabs: ['practice'] };
console.log(mergeDeep(defaults, preferences));
console.log(defaults.editor.fontSize, preferences.editor.fontSize);

Problem: Implement a helper that follows a dotted path through an object. Return undefined if a path segment is missing, null, or not an object, and only follow own properties.

javascript

function getOwnPath(source, path) {
  let current = source;
  for (const key of path.split('.')) {
    if (current === null || typeof current !== 'object' ||
        !Object.hasOwn(current, key)) return undefined;
    current = current[key];
  }
  return current;
}

const profile = { account: { contact: { email: 'maya@example.test' } } };
console.log(getOwnPath(profile, 'account.contact.email'));
console.log(getOwnPath(profile, 'account.address.city'));

Problem: Write a recursive equality check for acyclic JSON-like values. Array order matters, but object property order does not.

javascript

function deepEqual(left, right) {
  if (Object.is(left, right)) return true;
  if (left === null || right === null ||
      typeof left !== 'object' || typeof right !== 'object') return false;
  if (Array.isArray(left) !== Array.isArray(right)) return false;

  const leftKeys = Object.keys(left);
  const rightKeys = Object.keys(right);
  if (leftKeys.length !== rightKeys.length) return false;
  return leftKeys.every((key) =>
    Object.hasOwn(right, key) && deepEqual(left[key], right[key])
  );
}

console.log(deepEqual({ point: [3, 8], label: 'A' }, { label: 'A', point: [3, 8] }));
console.log(deepEqual({ point: [3, 8] }, { point: [8, 3] }));