๐ŸŽ“ Velnov

๐ŸŸจ 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.

Key concepts in this topic

ObjectsLiteralsDot notationBracket notationDynamic keysundefinedOptional chainingAdding propertiesconstdeletenullin operatorhasOwnObject.keysIterationObject.entriesDestructuringMethodsthisArrow functionsES6SpreadCopyingShallow copy

Jump to: Easy ยท Medium ยท Hard

Easy questions (5)

Q1. easy

Which line creates an object?

  1. A const user = { name: "Ana", age: 21 };
  2. B const user = [ name: "Ana" ];
  3. C const user = ( name: "Ana" );
  4. D const user = object(name, age);

Answer: A โ€” const user = { name: "Ana", age: 21 };

Curly braces with key: value pairs create an object literal - the most common way to group related data.

ObjectsLiterals

Q2. easy

What are the two ways to read a property?

console.log(user.name);
console.log(user["name"]);
const key = "name";
console.log(user[key]);   // dynamic - brackets required
  1. A Dot notation user.name and bracket notation user["name"]
  2. B Only dot notation
  3. C user->name
  4. D user::name

Answer: A โ€” Dot notation user.name and bracket notation user["name"]

Dot notation is cleaner; brackets are required when the key is stored in a variable or is not a valid identifier.

Dot notationBracket notation

Q4. easy

What happens when you read a property that does not exist? console.log(user.email);

  1. A undefined
  2. B null
  3. C ReferenceError
  4. D ""

Answer: A โ€” undefined

Missing properties return undefined rather than throwing. But reading a property OF undefined (user.address.city when address is missing) throws a TypeError.

undefinedOptional chaining

Q5. easy

How do you ADD a new property to an existing object?

  1. A user.email = "a@b.com";
  2. B user.add("email", "a@b.com");
  3. C user.push({email: "a@b.com"});
  4. D You cannot add properties later

Answer: A โ€” user.email = "a@b.com";

Assigning to a new key creates it; assigning to an existing key updates it. Objects are dynamic - even const objects can gain properties.

Adding propertiesconst

Q10. easy

What is a method?

const user = {
  name: "Ana",
  greet() { return `Hi, ${this.name}`; }
};
console.log(user.greet());   // Hi, Ana
  1. A A function stored as an object property
  2. B A special kind of variable
  3. C A loop
  4. D A class only

Answer: A โ€” A function stored as an object property

When a property's value is a function, it is called a method and can act on the object's own data via this.

Methodsthis

Medium questions (17)

Q3. medium

When MUST you use bracket notation?

const obj = { "first name": "Ana" };
console.log(obj["first name"]);   // brackets required
  1. A When the key is in a variable, has spaces/hyphens, or starts with a digit
  2. B Never - dot always works
  3. C Only for numbers
  4. 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?

  1. A delete user.age;
  2. B user.age = null;
  3. C user.remove("age");
  4. 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"));
  1. A "name" in user or Object.hasOwn(user, "name")
  2. B user.has("name")
  3. C user.contains("name")
  4. 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]]
  1. A Arrays of keys, of values, and of [key, value] pairs
  2. B Objects
  3. C Strings
  4. 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?

  1. A for (const [k, v] of Object.entries(obj))
  2. B for (const v of obj)
  3. C obj.forEach((k, v) => ...)
  4. 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?

  1. A The object the method was called ON (user.greet() means this = user)
  2. B The global object always
  3. C The function itself
  4. 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
  1. A Creates variables name and age from the matching properties
  2. B Deletes the properties
  3. C Creates an array
  4. 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
  1. A Creates a SHALLOW copy with the same properties
  2. B Creates a deep copy
  3. C Deletes properties
  4. 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 };
  1. A { ...obj1, ...obj2 } or Object.assign({}, obj1, obj2)
  2. B obj1 + obj2
  3. C obj1.merge(obj2)
  4. 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 }
  1. A When the key and variable have the same name, you can write it once - equals { name: name }
  2. B It creates an empty property
  3. C SyntaxError
  4. 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
  1. A Square brackets let you use a VARIABLE's value as the key - giving { score: 100 }
  2. B They create an array property
  3. C They compute a number
  4. 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"));
  1. A Converts the object into a JSON STRING for storage or sending
  2. B Parses a string into an object
  3. C Copies the object
  4. 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"
  1. A Prevents adding, removing or changing properties (shallowly)
  2. B Deletes the object
  3. C Makes it faster
  4. 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);

  1. A false - objects compare by REFERENCE, not contents
  2. B true
  3. C undefined
  4. 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
  1. A Object.keys(obj).length
  2. B obj.length
  3. C obj.size
  4. 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
  1. A Destructures the parameter object, so callers pass one object and you get named variables
  2. B Requires two arguments
  3. C Creates an object
  4. 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
  1. A Object.values(obj).reduce((a, b) => a + b, 0)
  2. B obj.sum()
  3. C obj.reduce(...)
  4. 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
};
  1. A Arrow functions have no own this - it comes from the outer scope, not the object
  2. B Template literals cannot use this
  3. C greet must be called with new
  4. 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
  1. A 99 - spread is SHALLOW, so the nested object is shared
  2. B 1
  3. C undefined
  4. 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?

  1. A user?.address?.city - optional chaining returns undefined instead of throwing
  2. B user.address.city
  3. C user!address!city
  4. 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
  1. A Functions, undefined values, Dates become strings, and Map/Set are destroyed
  2. B Nothing - it is a perfect copy
  3. C Only numbers
  4. 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
  1. A const locks the BINDING (the variable cannot point elsewhere), not the object's contents
  2. B It is a bug
  3. C const only works for numbers
  4. 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"));
  1. A Map allows ANY key type, preserves insertion order, has .size, and is optimised for frequent additions/removals
  2. B They are identical
  3. C Map only stores numbers
  4. 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);

  1. A { b: 2, c: 3 } - rest collects the remaining properties
  2. B { a: 1 }
  3. C [2, 3]
  4. 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
  1. A Calls getName only if it exists - otherwise returns undefined instead of throwing
  2. B Always calls it
  3. C Defines the method
  4. 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

Practice โ€œObjectsโ€ as a quiz