Practice Questions — Objects and JSON
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output of the following code?
const obj = { name: "Aarav", age: 15 };
console.log(obj.name);
console.log(obj.age);Dot notation accesses property values.
Aarav15Question 2
Easy
What is the output?
const student = { name: "Priya", grade: "10th" };
const key = "grade";
console.log(student[key]);Bracket notation lets you use a variable as the key.
10thQuestion 3
Easy
What is the output?
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));Object.keys returns an array of property names.
["a", "b", "c"]Question 4
Easy
What is the output?
const obj = { x: 10, y: 20 };
obj.z = 30;
console.log(obj);You can add properties to objects at any time.
{ x: 10, y: 20, z: 30 }Question 5
Easy
What is the output?
const scores = { maths: 95, science: 88 };
console.log(Object.values(scores));Object.values returns an array of property values.
[95, 88]Question 6
Easy
What is the output?
const { name, age } = { name: "Rohan", age: 16, grade: "11th" };
console.log(name);
console.log(age);Destructuring extracts specific properties into variables.
Rohan16Question 7
Medium
What is the output?
const person = {
name: "Kavya",
greet() {
return "Hi, " + this.name;
}
};
console.log(person.greet());this refers to the object the method belongs to.
Hi, KavyaQuestion 8
Medium
What is the output?
const a = { x: 1 };
const b = { ...a, y: 2 };
console.log(b);
console.log(a);Spread copies properties into a new object.
{ x: 1, y: 2 }{ x: 1 }Question 9
Medium
What is the output?
const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj);
console.log(entries);Object.entries returns [key, value] pairs.
[["a", 1], ["b", 2], ["c", 3]]Question 10
Medium
What is the output?
const student = {
name: "Diya",
address: {
city: "Chennai",
state: "Tamil Nadu"
}
};
console.log(student.address.city);
console.log(student.phone?.number);Optional chaining (?.) returns undefined for missing properties instead of throwing an error.
ChennaiundefinedQuestion 11
Medium
What is the output?
const obj = { name: "Vikram" };
const json = JSON.stringify(obj);
console.log(json);
console.log(typeof json);JSON.stringify converts an object to a string.
{"name":"Vikram"}stringQuestion 12
Medium
What is the output?
const defaults = { color: "red", size: 10 };
const custom = { size: 20, weight: 5 };
const merged = { ...defaults, ...custom };
console.log(merged);When spreading, later properties overwrite earlier ones with the same key.
{ color: "red", size: 20, weight: 5 }Question 13
Hard
What is the output?
const a = { data: [1, 2, 3] };
const b = { ...a };
b.data.push(4);
console.log(a.data);Spread creates a shallow copy. What happens to nested arrays?
[1, 2, 3, 4]Question 14
Hard
What is the output?
const a = { name: "Meera" };
const b = { name: "Meera" };
const c = a;
console.log(a === b);
console.log(a === c);Objects are compared by reference, not content.
falsetrueQuestion 15
Hard
What is the output?
const { name: studentName, age: studentAge = 18 } = { name: "Arjun" };
console.log(studentName);
console.log(studentAge);Renaming and default values in destructuring.
Arjun18Question 16
Hard
What is the output?
const person = {
name: "Aarav",
greet: () => {
return "Hi, " + this.name;
}
};
console.log(person.greet());Arrow functions do NOT have their own this.
Hi, undefinedQuestion 17
Medium
What is the difference between dot notation and bracket notation for accessing object properties?
When can you use each one?
Dot notation (
obj.key) is simpler and more common. Bracket notation (obj["key"]) is required when the key contains spaces or special characters, when the key is stored in a variable, or when the key is computed dynamically. Dot notation only works with valid identifier names.Question 18
Hard
What is the output?
const student = {
name: "Priya",
marks: { maths: 92, science: 88 }
};
const { marks: { maths, science } } = student;
console.log(maths);
console.log(science);Nested destructuring extracts values from nested objects.
9288Question 19
Easy
What is the output?
const obj = { a: 1, b: 2, c: 3 };
delete obj.b;
console.log(obj);delete removes a property from an object.
{ a: 1, c: 3 }Question 20
Medium
What is the output?
const json = '{"name":"Diya","age":14}';
const obj = JSON.parse(json);
console.log(obj.name);
console.log(typeof obj);JSON.parse converts a JSON string to a JavaScript object.
DiyaobjectMixed & Application Questions
Question 1
Easy
What is the output?
const person = { name: "Kabir", age: 17 };
console.log("name" in person);
console.log("email" in person);The in operator checks if a property exists in an object.
truefalseQuestion 2
Easy
What is the output?
const obj = { x: 10, y: 20, z: 30 };
const sum = Object.values(obj).reduce((a, b) => a + b, 0);
console.log(sum);Extract values as an array, then reduce to sum.
60Question 3
Medium
What is the output?
const obj = { a: 1, b: 2, c: 3 };
const filtered = Object.entries(obj)
.filter(([key, val]) => val > 1)
.map(([key, val]) => key);
console.log(filtered);Convert to entries, filter by value, extract keys.
["b", "c"]Question 4
Medium
What is the output?
const student = { name: "Ananya", grade: "10th" };
const { name, ...rest } = student;
console.log(name);
console.log(rest);Rest pattern collects remaining properties.
Ananya{ grade: "10th" }Question 5
Medium
What is the output?
const key = "color";
const value = "purple";
const obj = { [key]: value };
console.log(obj);Square brackets in an object literal create a computed property name.
{ color: "purple" }Question 6
Hard
What is the output?
const students = [
{ name: "Aarav", marks: 72 },
{ name: "Priya", marks: 91 },
{ name: "Rohan", marks: 85 },
{ name: "Diya", marks: 68 }
];
const names = students
.filter(s => s.marks >= 70)
.sort((a, b) => b.marks - a.marks)
.map(s => s.name);
console.log(names);Filter >= 70, sort descending, extract names.
["Priya", "Rohan", "Aarav"]Question 7
Hard
What is the output?
const obj = {
count: 0,
increment() {
this.count++;
return this;
},
getCount() {
return this.count;
}
};
console.log(obj.increment().increment().increment().getCount());Each increment returns this (the object), enabling chaining.
3Question 8
Hard
What is the output?
const data = '{"students":[{"name":"Meera","score":88},{"name":"Kabir","score":92}]}';
const parsed = JSON.parse(data);
console.log(parsed.students[1].name);
console.log(parsed.students.length);Parse the JSON string, then navigate the nested structure.
Kabir2Question 9
Medium
What is the output?
const obj = { a: 1, b: 2 };
const copy = Object.assign({}, obj, { c: 3 });
console.log(copy);
console.log(obj);Object.assign copies properties from source objects to a target.
{ a: 1, b: 2, c: 3 }{ a: 1, b: 2 }Question 10
Hard
What is the difference between a shallow copy and a deep copy of an object? How do you create each?
Think about what happens with nested objects and arrays.
A shallow copy copies top-level properties by value for primitives but by reference for nested objects/arrays. Changes to nested data in the copy affect the original. Create with
{ ...obj } or Object.assign({}, obj). A deep copy creates completely independent copies at all nesting levels. Create with structuredClone(obj) or JSON.parse(JSON.stringify(obj)).Question 11
Easy
What is the output?
const obj = { name: "Ishaan", age: 13 };
console.log(obj.hasOwnProperty("name"));
console.log(obj.hasOwnProperty("email"));hasOwnProperty checks if the object directly has the property.
truefalseQuestion 12
Hard
What is the output?
const people = [
{ name: "Aarav", city: "Delhi" },
{ name: "Priya", city: "Mumbai" },
{ name: "Rohan", city: "Delhi" },
{ name: "Diya", city: "Mumbai" }
];
const grouped = people.reduce((acc, person) => {
const city = person.city;
acc[city] = acc[city] || [];
acc[city].push(person.name);
return acc;
}, {});
console.log(grouped);reduce groups people by city into an object.
{ Delhi: ["Aarav", "Rohan"], Mumbai: ["Priya", "Diya"] }Question 13
Medium
What is the output?
const obj = { a: 1, b: 2, c: 3 };
for (const [key, val] of Object.entries(obj)) {
console.log(key + " = " + val);
}Destructuring in the for...of loop unpacks each [key, value] pair.
a = 1b = 2c = 3Multiple Choice Questions
MCQ 1
How do you create an object in JavaScript?
Answer: B
B is correct. Objects are created with curly braces
B is correct. Objects are created with curly braces
{}. Square brackets [] (option A) create arrays. The other syntaxes are not valid.MCQ 2
What does Object.keys(obj) return?
Answer: C
C is correct.
C is correct.
Object.keys() returns an array of property names (strings). Object.values() returns values (option A). Object.entries() returns pairs (option B).MCQ 3
When must you use bracket notation instead of dot notation?
Answer: B
B is correct. Bracket notation is required when the key contains spaces or special characters (
B is correct. Bracket notation is required when the key contains spaces or special characters (
obj["full name"]), when the key is stored in a variable (obj[key]), or when it is computed dynamically.MCQ 4
What does JSON stand for?
Answer: C
C is correct. JSON stands for JavaScript Object Notation. It is a text format for representing data that looks like JavaScript objects but with stricter rules (all keys must be double-quoted).
C is correct. JSON stands for JavaScript Object Notation. It is a text format for representing data that looks like JavaScript objects but with stricter rules (all keys must be double-quoted).
MCQ 5
What does delete obj.key do?
Answer: C
C is correct. The
C is correct. The
delete operator completely removes the property from the object. After deletion, the property no longer exists (not null, not undefined - gone).MCQ 6
What happens when you use === to compare two objects with identical content?
Answer: B
B is correct.
B is correct.
=== compares objects by reference (memory address), not by content. Two different objects with identical content are different references, so === returns false.MCQ 7
Why should you NOT use arrow functions as object methods?
Answer: B
B is correct. Arrow functions do not have their own
B is correct. Arrow functions do not have their own
this. They inherit this from the enclosing scope, which is usually NOT the object. So this.propertyName inside an arrow method will be undefined.MCQ 8
What does JSON.stringify do?
Answer: C
C is correct.
C is correct.
JSON.stringify converts a JavaScript object to a JSON string. JSON.parse does the opposite (option A).MCQ 9
What does the spread operator { ...obj } create?
Answer: B
B is correct. The spread operator creates a shallow copy. Top-level primitive properties are copied by value, but nested objects and arrays are copied by reference (shared). Use
B is correct. The spread operator creates a shallow copy. Top-level primitive properties are copied by value, but nested objects and arrays are copied by reference (shared). Use
structuredClone for deep copies.MCQ 10
What is optional chaining (?.) used for?
Answer: B
B is correct. Optional chaining
B is correct. Optional chaining
?. safely accesses nested properties. If any part of the chain is null or undefined, it short-circuits and returns undefined instead of throwing a TypeError.MCQ 11
What is the result of typeof null?
Answer: C
C is correct.
C is correct.
typeof null returns "object". This is a well-known bug in JavaScript from its early implementation. null is NOT actually an object - it is its own type. This has never been fixed for backward compatibility.MCQ 12
What is the modern way to create a deep copy of an object?
Answer: C
C is correct.
C is correct.
structuredClone() creates a true deep copy of an object, including nested structures. Options A and B create shallow copies. Option D is not a real method.MCQ 13
What types of values are NOT allowed in JSON?
Answer: C
C is correct. JSON only supports strings, numbers, booleans, null, arrays, and objects. Functions, undefined, Symbol, Infinity, and NaN are NOT valid JSON values.
C is correct. JSON only supports strings, numbers, booleans, null, arrays, and objects. Functions, undefined, Symbol, Infinity, and NaN are NOT valid JSON values.
JSON.stringify silently omits these.MCQ 14
What does Object.entries({ a: 1, b: 2 }) return?
Answer: C
C is correct.
C is correct.
Object.entries() returns an array of [key, value] pairs. Each property becomes a two-element array. Option A is Object.keys(). Option B is Object.values().MCQ 15
What is the output of: const obj = {}; console.log(typeof obj);
Answer: B
B is correct. An empty object is still an object.
B is correct. An empty object is still an object.
typeof {} returns "object". It is not "empty" or "undefined" - those are not valid typeof results for objects.MCQ 16
What is the shorthand for { name: name, age: age } in ES6?
Answer: A
A is correct. When the property name and variable name are the same, you can use the shorthand
A is correct. When the property name and variable name are the same, you can use the shorthand
{ name, age } instead of { name: name, age: age }. This is called shorthand property notation in ES6.MCQ 17
What does Object.freeze(obj) do?
Answer: B
B is correct.
B is correct.
Object.freeze() makes an object immutable at the top level. You cannot add, remove, or modify properties. It is a shallow freeze - nested objects can still be modified.Coding Challenges
Challenge 1: Student Report Card
EasyAarav has a student object: {name: "Aarav", marks: {maths: 92, science: 88, english: 76, hindi: 82}}. Write a program that calculates the total marks, average, and percentage.
Sample Input
(No input required)
Sample Output
Student: Aarav
Total: 338 / 400
Average: 84.5
Percentage: 84.5%
Use Object.values to extract marks. Use reduce to calculate the total.
const student = {
name: "Aarav",
marks: { maths: 92, science: 88, english: 76, hindi: 82 }
};
const values = Object.values(student.marks);
const total = values.reduce((a, b) => a + b, 0);
const maxTotal = values.length * 100;
const avg = total / values.length;
console.log("Student:", student.name);
console.log("Total:", total, "/", maxTotal);
console.log("Average:", avg);
console.log("Percentage:", avg + "%");Challenge 2: Merge User Preferences
EasyPriya has default settings {theme: "dark", fontSize: 14, lang: "en", notifications: true} and user preferences {fontSize: 18, lang: "hi"}. Merge them so user preferences override defaults.
Sample Input
(No input required)
Sample Output
{ theme: "dark", fontSize: 18, lang: "hi", notifications: true }
Use the spread operator to merge.
const defaults = { theme: "dark", fontSize: 14, lang: "en", notifications: true };
const userPrefs = { fontSize: 18, lang: "hi" };
const settings = { ...defaults, ...userPrefs };
console.log(settings);Challenge 3: Build Product Cards from Objects
MediumRohan has an array of product objects: [{name: "Laptop", price: 45000, rating: 4.5}, {name: "Phone", price: 15000, rating: 4.2}, {name: "Watch", price: 8000, rating: 4.8}]. Use map and template literals to generate HTML card strings for each product.
Sample Input
(No input required)
Sample Output
(Three HTML cards with product name, price, and star rating)
Use map with template literals. Include price formatted with commas.
const products = [
{ name: "Laptop", price: 45000, rating: 4.5 },
{ name: "Phone", price: 15000, rating: 4.2 },
{ name: "Watch", price: 8000, rating: 4.8 }
];
const cards = products.map(p => `<div class="product-card">
<h3>${p.name}</h3>
<p class="price">Rs ${p.price.toLocaleString()}</p>
<p class="rating">${p.rating} / 5</p>
</div>`);
console.log(cards.join("\n"));Challenge 4: Object Difference Checker
MediumKavya wants to compare two versions of a student object and find what changed. Write a function diff(oldObj, newObj) that returns an object showing only the properties that changed.
Sample Input
diff({name: "Kavya", age: 15, grade: "10th"}, {name: "Kavya", age: 16, grade: "11th"})
Sample Output
{ age: { old: 15, new: 16 }, grade: { old: "10th", new: "11th" } }
Compare each property. Only include properties that changed.
function diff(oldObj, newObj) {
const changes = {};
for (const key of Object.keys(newObj)) {
if (oldObj[key] !== newObj[key]) {
changes[key] = { old: oldObj[key], new: newObj[key] };
}
}
return changes;
}
const result = diff(
{ name: "Kavya", age: 15, grade: "10th" },
{ name: "Kavya", age: 16, grade: "11th" }
);
console.log(result);Challenge 5: Invert Object Keys and Values
MediumVikram has the object {a: 1, b: 2, c: 3}. Write a function invertObject that swaps keys and values, returning {1: "a", 2: "b", 3: "c"}.
Sample Input
invertObject({a: 1, b: 2, c: 3})
Sample Output
{ 1: "a", 2: "b", 3: "c" }
Use Object.entries and reduce.
function invertObject(obj) {
return Object.entries(obj).reduce((acc, [key, val]) => {
acc[val] = key;
return acc;
}, {});
}
console.log(invertObject({ a: 1, b: 2, c: 3 }));Challenge 6: Deep Flatten Nested Object
HardArjun has a deeply nested object: {a: 1, b: {c: 2, d: {e: 3, f: 4}}, g: 5}. Write a function flattenObject that returns {a: 1, "b.c": 2, "b.d.e": 3, "b.d.f": 4, g: 5}.
Sample Input
flattenObject({a: 1, b: {c: 2, d: {e: 3}}})
Sample Output
{a: 1, "b.c": 2, "b.d.e": 3}
Use recursion. Concatenate keys with dots for nesting.
function flattenObject(obj, prefix = "") {
const result = {};
for (const [key, val] of Object.entries(obj)) {
const newKey = prefix ? prefix + "." + key : key;
if (typeof val === "object" && val !== null && !Array.isArray(val)) {
Object.assign(result, flattenObject(val, newKey));
} else {
result[newKey] = val;
}
}
return result;
}
console.log(flattenObject({ a: 1, b: { c: 2, d: { e: 3, f: 4 } }, g: 5 }));Challenge 7: Student Ranking System
HardMeera has student data as an array of objects. Write a function that takes the array, calculates each student's average, adds a rank property (1 = highest average), and returns the sorted array.
Sample Input
[{name: "Aarav", marks: [85, 90, 78]}, {name: "Priya", marks: [92, 88, 95]}, {name: "Rohan", marks: [70, 65, 80]}]
Sample Output
[{name: "Priya", marks: [...], average: 91.67, rank: 1}, ...]
Use map, sort, and forEach. Do not modify the original array.
function rankStudents(students) {
return students
.map(s => ({
...s,
average: parseFloat((s.marks.reduce((a, b) => a + b, 0) / s.marks.length).toFixed(2))
}))
.sort((a, b) => b.average - a.average)
.map((s, i) => ({ ...s, rank: i + 1 }));
}
const data = [
{ name: "Aarav", marks: [85, 90, 78] },
{ name: "Priya", marks: [92, 88, 95] },
{ name: "Rohan", marks: [70, 65, 80] }
];
console.log(rankStudents(data));Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn web development with a live mentor?
Explore our Frontend Masterclass