๐จ JavaScript ยท Topic 10 of 20
Objects โ JavaScript Questions with Answers
30 practice questions on Objects, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
5 easy ยท 17 medium ยท 8 hard ยท Part of JavaScript: The language of the web - basics to advanced, 20 topics.
Medium questions (17)
Q3. medium
When MUST you use bracket notation?
const obj = { "first name": "Ana" };
console.log(obj["first name"]); // brackets required
- A When the key is in a variable, has spaces/hyphens, or starts with a digit
- B Never - dot always works
- C Only for numbers
- D Only inside functions
Answer: A โ When the key is in a variable, has spaces/hyphens, or starts with a digit
obj.key looks for the literal key named 'key'; obj[key] uses the variable's value. Keys like "first name" or "data-id" also need brackets.
Bracket notationDynamic keys
Q6. medium
How do you DELETE a property?
- A delete user.age;
- B user.age = null;
- C user.remove("age");
- D user.age.delete();
Answer: A โ delete user.age;
delete removes the key entirely, so "age" in user becomes false. Setting it to null keeps the key with a null value - a meaningful difference when iterating.
deletenull
Q7. medium
How do you check whether an object HAS a property?
console.log("name" in user);
console.log(Object.hasOwn(user, "name"));
- A "name" in user or Object.hasOwn(user, "name")
- B user.has("name")
- C user.contains("name")
- D user.exists("name")
Answer: A โ "name" in user or Object.hasOwn(user, "name")
'in' also finds inherited properties; Object.hasOwn (or hasOwnProperty) checks only the object's own keys. Testing user.name !== undefined fails when the value legitimately IS undefined.
in operatorhasOwn
Q8. medium
What do Object.keys(), Object.values() and Object.entries() return?
const u = { a: 1, b: 2 };
Object.keys(u); // ["a", "b"]
Object.values(u); // [1, 2]
Object.entries(u); // [["a",1], ["b",2]]
- A Arrays of keys, of values, and of [key, value] pairs
- B Objects
- C Strings
- D Numbers
Answer: A โ Arrays of keys, of values, and of [key, value] pairs
They convert an object into arrays so you can use array methods on it - the standard way to iterate or transform objects.
Object.keysIteration
Q9. medium
How do you loop over an object's key/value pairs?
- A for (const [k, v] of Object.entries(obj))
- B for (const v of obj)
- C obj.forEach((k, v) => ...)
- D for (const k of obj)
Answer: A โ for (const [k, v] of Object.entries(obj))
Plain objects are not iterable, so for...of on the object itself throws. Object.entries plus destructuring is the modern approach (for...in also works, giving keys only).
Object.entriesDestructuring
Q11. medium
What does this refer to inside a regular object method?
- A The object the method was called ON (user.greet() means this = user)
- B The global object always
- C The function itself
- D undefined
Answer: A โ The object the method was called ON (user.greet() means this = user)
this is determined by HOW the function is called - the object before the dot. Arrow functions are the exception: they inherit this from the surrounding scope.
thisMethods
Q13. medium
What does object destructuring do?
const { name, age } = user;
const { name, age } = user;
const { name: userName } = user; // rename
const { city = "Unknown" } = user; // default
- A Creates variables name and age from the matching properties
- B Deletes the properties
- C Creates an array
- D SyntaxError
Answer: A โ Creates variables name and age from the matching properties
Destructuring extracts properties by NAME (order does not matter, unlike arrays). Widely used for function parameters and imports.
DestructuringES6
Q14. medium
What does the spread operator do with objects?
const copy = { ...user };
const copy = { ...user };
const merged = { ...defaults, ...userSettings }; // later wins
- A Creates a SHALLOW copy with the same properties
- B Creates a deep copy
- C Deletes properties
- D Creates an array
Answer: A โ Creates a SHALLOW copy with the same properties
Spread copies top-level properties into a new object. Nested objects are still shared - use structuredClone() for a deep copy.
SpreadCopying
Q16. medium
How do you MERGE two objects?
const settings = { ...defaults, ...userPrefs };
- A { ...obj1, ...obj2 } or Object.assign({}, obj1, obj2)
- B obj1 + obj2
- C obj1.merge(obj2)
- D obj1.concat(obj2)
Answer: A โ { ...obj1, ...obj2 } or Object.assign({}, obj1, obj2)
Both merge left to right, so later sources overwrite earlier keys. Note Object.assign(obj1, obj2) MUTATES obj1 - pass {} as the first argument to avoid that.
SpreadObject.assign
Q17. medium
What is shorthand property syntax?
const name = "Ana";
const user = { name };
const name = "Ana", age = 21;
const user = { name, age }; // { name: "Ana", age: 21 }
- A When the key and variable have the same name, you can write it once - equals { name: name }
- B It creates an empty property
- C SyntaxError
- D It creates a string
Answer: A โ When the key and variable have the same name, you can write it once - equals { name: name }
ES6 shorthand removes repetition, very common when building objects from existing variables or returning several values.
ShorthandES6
Q18. medium
What are computed property names?
const key = "score";
const obj = { [key]: 100 };
const field = "email";
setForm({ ...form, [field]: value }); // React pattern
- A Square brackets let you use a VARIABLE's value as the key - giving { score: 100 }
- B They create an array property
- C They compute a number
- D SyntaxError
Answer: A โ Square brackets let you use a VARIABLE's value as the key - giving { score: 100 }
Without brackets the key would literally be "key". Computed keys are essential for dynamic objects built from data or form fields.
Computed keysDynamic
Q20. medium
What does JSON.stringify(obj) do?
localStorage.setItem("user", JSON.stringify(user));
const back = JSON.parse(localStorage.getItem("user"));
- A Converts the object into a JSON STRING for storage or sending
- B Parses a string into an object
- C Copies the object
- D Validates the object
Answer: A โ Converts the object into a JSON STRING for storage or sending
stringify serialises to text (dropping functions and undefined); JSON.parse does the reverse. Essential for localStorage and API requests.
JSONlocalStorage
Q22. medium
What does Object.freeze(obj) do?
const config = Object.freeze({ api: "/v1" });
config.api = "/v2"; // ignored
console.log(config.api); // "/v1"
- A Prevents adding, removing or changing properties (shallowly)
- B Deletes the object
- C Makes it faster
- D Converts it to a string
Answer: A โ Prevents adding, removing or changing properties (shallowly)
Frozen objects silently ignore changes (or throw in strict mode). It is shallow - nested objects can still change unless frozen too.
Object.freezeImmutability
Q24. medium
What is the output?
const a = { x: 1 };
const b = { x: 1 };
console.log(a === b);
- A false - objects compare by REFERENCE, not contents
- B true
- C undefined
- D Error
Answer: A โ false - objects compare by REFERENCE, not contents
Two separately created objects are never ===, even with identical contents. Compare contents with JSON.stringify or a per-key check.
Reference equality
Q25. medium
How do you count an object's properties?
console.log(Object.keys({a:1, b:2}).length); // 2
- A Object.keys(obj).length
- B obj.length
- C obj.size
- D obj.count()
Answer: A โ Object.keys(obj).length
Objects have no length property (that is arrays). Convert the keys to an array and measure it. (A Map does have .size.)
Object.keyslength
Q27. medium
What does this shorthand do?
function show({ name, age }) { }
function show({ name, age = 0 }) {
console.log(name, age);
}
show({ age: 21, name: "Ana" }); // order-free
- A Destructures the parameter object, so callers pass one object and you get named variables
- B Requires two arguments
- C Creates an object
- D SyntaxError
Answer: A โ Destructures the parameter object, so callers pass one object and you get named variables
Parameter destructuring makes call sites self-documenting and order-independent - very common in modern APIs and React components.
DestructuringParameters
Q29. medium
How do you convert an object to an array of values and sum them?
const scores = { math: 90, sci: 80 };
console.log(Object.values(scores).reduce((a,b) => a+b, 0)); // 170
- A Object.values(obj).reduce((a, b) => a + b, 0)
- B obj.sum()
- C obj.reduce(...)
- D Object.sum(obj)
Answer: A โ Object.values(obj).reduce((a, b) => a + b, 0)
Objects have no array methods, so convert first with Object.values() and then use reduce. The same pattern applies with keys and entries.
Object.valuesreduce
Hard questions (8)
Q12. hard
Why does this break?
const user = { name: "Ana", greet: () => `Hi ${this.name}` };
const user = {
name: "Ana",
greet() { return `Hi ${this.name}`; } // works
};
- A Arrow functions have no own this - it comes from the outer scope, not the object
- B Template literals cannot use this
- C greet must be called with new
- D It works fine
Answer: A โ Arrow functions have no own this - it comes from the outer scope, not the object
An arrow function as an object method captures this from where the object was DEFINED (often the module or window), so this.name is undefined. Use shorthand method syntax instead.
Arrow functionsthis
Q15. hard
What is the output?
const a = { x: { y: 1 } };
const b = { ...a };
b.x.y = 99;
console.log(a.x.y);
const deep = structuredClone(a);
deep.x.y = 99;
console.log(a.x.y); // 1 - safe
- A 99 - spread is SHALLOW, so the nested object is shared
- B 1
- C undefined
- D Error
Answer: A โ 99 - spread is SHALLOW, so the nested object is shared
Only the top level was copied; a.x and b.x point to the same inner object. structuredClone(a) or JSON round-tripping gives a true deep copy.
Shallow copystructuredClone
Q19. hard
How do you safely read a deeply nested property that might be missing?
- A user?.address?.city - optional chaining returns undefined instead of throwing
- B user.address.city
- C user!address!city
- D try { user.address.city } only
Answer: A โ user?.address?.city - optional chaining returns undefined instead of throwing
Without ?., reading .city on undefined throws 'Cannot read properties of undefined'. Combine with ?? for a default: user?.address?.city ?? "N/A".
Optional chainingNullish coalescing
Q21. hard
What is lost when you copy an object via JSON.parse(JSON.stringify(obj))?
const deep = structuredClone(obj); // preferred
- A Functions, undefined values, Dates become strings, and Map/Set are destroyed
- B Nothing - it is a perfect copy
- C Only numbers
- D The keys
Answer: A โ Functions, undefined values, Dates become strings, and Map/Set are destroyed
The JSON round-trip is a quick deep copy but only supports JSON types. structuredClone() handles Dates, Maps, Sets and cycles properly.
Deep copystructuredClone
Q23. hard
Why can you modify a const object's properties?
const u = { n: 1 };
u.n = 2; // allowed
// u = {}; // TypeError
- A const locks the BINDING (the variable cannot point elsewhere), not the object's contents
- B It is a bug
- C const only works for numbers
- D You cannot modify them
Answer: A โ const locks the BINDING (the variable cannot point elsewhere), not the object's contents
const guarantees the variable always refers to the same object; the object itself remains mutable. Use Object.freeze() if you need the contents locked too.
constMutability
Q26. hard
What is the difference between an Object and a Map?
const m = new Map();
m.set("a", 1);
m.set(userObj, "data"); // object as key!
console.log(m.size, m.get("a"));
- A Map allows ANY key type, preserves insertion order, has .size, and is optimised for frequent additions/removals
- B They are identical
- C Map only stores numbers
- D Object is newer
Answer: A โ Map allows ANY key type, preserves insertion order, has .size, and is optimised for frequent additions/removals
Object keys are strings/symbols only; Map keys can be objects, numbers, anything. Use Object for records and JSON; use Map for dictionaries with dynamic or non-string keys.
MapData structures
Q28. hard
What is the output?
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(rest);
- A { b: 2, c: 3 } - rest collects the remaining properties
- B { a: 1 }
- C [2, 3]
- D undefined
Answer: A โ { b: 2, c: 3 } - rest collects the remaining properties
Rest in destructuring gathers everything not explicitly named - a neat way to remove a property without mutating: const { password, ...safeUser } = user.
RestDestructuring
Q30. hard
What does optional chaining with a function call do?
user.getName?.()
onSuccess?.(data); // call the callback only if provided
- A Calls getName only if it exists - otherwise returns undefined instead of throwing
- B Always calls it
- C Defines the method
- D SyntaxError
Answer: A โ Calls getName only if it exists - otherwise returns undefined instead of throwing
?.() guards against 'x is not a function' errors, useful for optional callbacks. Similarly arr?.[0] guards array access.
Optional chainingCallbacks