Practice Questions — ES6+ Modern JavaScript Features
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output?
const x = 10;
let y = 20;
y = 30;
console.log(x, y);const cannot be reassigned, let can.
10 30Question 2
Easy
What is the output?
const double = n => n * 2;
console.log(double(7));Arrow function with single parameter and implicit return.
14Question 3
Easy
What is the output?
const [a, b, c] = ["red", "green", "blue"];
console.log(b);Array destructuring maps by position.
greenQuestion 4
Easy
What is the output?
const { name, age } = { name: "Kavya", age: 14, city: "Pune" };
console.log(name, age);Object destructuring extracts named properties.
Kavya 14Question 5
Easy
What is the output?
const arr = [1, 2, 3];
const merged = [...arr, 4, 5];
console.log(merged);Spread expands the array elements.
[1, 2, 3, 4, 5]Question 6
Medium
What is the output?
const [first, , third] = [10, 20, 30, 40];
console.log(first, third);The empty slot (comma with nothing) skips an element.
10 30Question 7
Medium
What is the output?
const { name: studentName, grade = "10th" } = { name: "Rohan" };
console.log(studentName);
console.log(grade);name: studentName renames. grade has a default because it is not in the object.
Rohan10thQuestion 8
Medium
What is the output?
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet("Aarav"));
console.log(greet());
console.log(greet(undefined));Default is used when no argument or undefined is passed.
Hello, Aarav!Hello, Guest!Hello, Guest!Question 9
Medium
What is the output?
const base = { a: 1, b: 2 };
const extra = { b: 3, c: 4 };
const merged = { ...base, ...extra };
console.log(merged);When spreading objects, later properties override earlier ones with the same key.
{ a: 1, b: 3, c: 4 }Question 10
Medium
What is the output?
const [first, ...rest] = [10, 20, 30, 40, 50];
console.log(first);
console.log(rest);
console.log(rest.length);Rest collects all remaining elements into an array.
10[20, 30, 40, 50]4Question 11
Medium
What is the output?
const user = { name: "Diya" };
console.log(user.address?.city);
console.log(user.address?.city ?? "Unknown");Optional chaining returns undefined when a level is missing.
undefinedUnknownQuestion 12
Hard
What is the output?
const { a: { b: value } = {} } = { a: { b: 42 } };
console.log(value);
const { a: { b: value2 } = {} } = {};
console.log(value2);In the first case, a exists. In the second, a is undefined so the default {} is used.
42undefinedQuestion 13
Hard
What is the output?
console.log(0 ?? "zero");
console.log(0 || "zero");
console.log("" ?? "empty");
console.log("" || "empty");
console.log(null ?? "null");
console.log(null || "null");?? triggers only on null/undefined. || triggers on any falsy value.
0zero (empty string)emptynullnullQuestion 14
Hard
What is the output?
function collect(first, ...middle, last) {
console.log(first, middle, last);
}
collect(1, 2, 3, 4, 5);Where must rest parameters appear?
SyntaxError: Rest parameter must be last formal parameterQuestion 15
Hard
What is the output?
const set = new Set([1, 2, 3, 2, 1]);
set.add(4);
set.add(2);
set.delete(1);
console.log([...set]);
console.log(set.size);Set removes duplicates. Adding an existing value does nothing.
[2, 3, 4]3Mixed & Application Questions
Question 1
Easy
What is the output?
const add = (a, b) => a + b;
const result = add(3, 4);
console.log(result);Arrow function with two parameters and implicit return.
7Question 2
Easy
What is the output?
const name = "Ankit";
const age = 16;
const student = { name, age };
console.log(student);Shorthand property syntax: { name } is the same as { name: name }.
{ name: "Ankit", age: 16 }Question 3
Medium
What is the output?
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b);Array destructuring swaps values without a temporary variable.
10 5Question 4
Medium
What is the output?
const key = "score";
const obj = { [key]: 95, [key + "Max"]: 100 };
console.log(obj);Computed property names use [expression] as the key.
{ score: 95, scoreMax: 100 }Question 5
Medium
What is the output?
const map = new Map();
map.set("a", 1);
map.set("b", 2);
map.set("a", 3);
console.log(map.get("a"));
console.log(map.size);Setting the same key again overwrites the value.
32Question 6
Medium
What is the output?
const arr = [1, 2, 3];
const copy = [...arr];
copy.push(4);
console.log(arr.length);
console.log(copy.length);Spread creates a new array. Changes to copy do not affect original.
34Question 7
Hard
What is the output?
const fn = () => ({ name: "test" });
const fn2 = () => { name: "test" };
console.log(fn());
console.log(fn2());Pay attention to the parentheses around the object literal.
{ name: "test" }undefinedQuestion 8
Hard
What is the output?
function test({ a, b = 10, ...rest }) {
console.log(a, b, rest);
}
test({ a: 1, b: 2, c: 3, d: 4 });
test({ a: 5, c: 6 });Destructure the parameter. b has a default. rest collects remaining properties.
1 2 { c: 3, d: 4 }5 10 { c: 6 }Question 9
Hard
What is the output?
if (true) {
var a = 1;
let b = 2;
const c = 3;
}
console.log(a);
console.log(typeof b);
console.log(typeof c);var escapes the block. let and const do not.
1undefinedundefinedQuestion 10
Hard
What is the output?
const nums = [5, 2, 8, 1, 9];
console.log(Math.max(...nums));
console.log(Math.min(...nums));
const all = [...nums, ...nums];
console.log(all.length);
console.log(new Set(all).size);Spread in function args. Spread in array creation. Set removes duplicates.
91105Multiple Choice Questions
MCQ 1
Which keyword should you use by default for declaring variables in modern JavaScript?
Answer: C
C is correct. Use
C is correct. Use
const by default. Only use let when you need to reassign. Never use var in modern code.MCQ 2
What is the short form of
const double = (n) => { return n * 2; };?Answer: B
B is correct. Single parameter can drop parentheses. Single expression can drop curly braces and return keyword.
B is correct. Single parameter can drop parentheses. Single expression can drop curly braces and return keyword.
n => n * 2 is the shortest form.MCQ 3
What does
const [a, b] = [10, 20] do?Answer: B
B is correct. This is array destructuring. It assigns the first element (10) to a and the second (20) to b.
B is correct. This is array destructuring. It assigns the first element (10) to a and the second (20) to b.
MCQ 4
What does the spread operator
... do with arrays?Answer: C
C is correct.
C is correct.
...[1,2,3] expands into 1, 2, 3 as individual values. Used in function calls, array creation, and object merging.MCQ 5
What is the difference between
let and const?Answer: B
B is correct.
B is correct.
let allows reassignment (let x = 1; x = 2;). const does not allow reassignment after declaration.MCQ 6
What does
const { name: n } = { name: "Aarav" }; do?Answer: B
B is correct. In destructuring,
B is correct. In destructuring,
name: n means 'take the name property and store it in a variable called n'. Only n is created, not name.MCQ 7
What does the rest operator (...) do in function parameters?
Answer: C
C is correct. In function parameters,
C is correct. In function parameters,
...args collects all remaining arguments into an array called args. It must be the last parameter.MCQ 8
What does
user.address?.city return when user.address is undefined?Answer: B
B is correct. Optional chaining
B is correct. Optional chaining
?. returns undefined when the chain is broken (when a property does not exist), instead of throwing a TypeError.MCQ 9
What is the result of
0 ?? 'default'?Answer: B
B is correct.
B is correct.
?? only replaces null and undefined. 0 is neither null nor undefined, so the left side (0) is returned.MCQ 10
Which data structure automatically removes duplicates?
Answer: D
D is correct.
D is correct.
Set only stores unique values. new Set([1,2,2,3,3,3]) results in Set {1, 2, 3}.MCQ 11
What is the difference between
for...in and for...of?Answer: B
B is correct.
B is correct.
for...in iterates over property names/keys (for objects) or indices (for arrays). for...of iterates over values (for arrays, strings, Maps, Sets).MCQ 12
Why does
const arr = [1,2]; arr.push(3); work even though arr is const?Answer: B
B is correct.
B is correct.
const prevents reassigning the variable (arr = something_else). But the array the variable points to CAN be modified (push, pop, etc.). The reference is constant, not the data.MCQ 13
How do you import a default export from a module?
Answer: C
C is correct. Default exports are imported without curly braces:
C is correct. Default exports are imported without curly braces:
import myName from './module.js'. You can use any name you want. Named exports use curly braces: import { name } from ....MCQ 14
What is template literal syntax in JavaScript?
Answer: C
C is correct. Template literals use backticks (`) and allow embedded expressions with
C is correct. Template literals use backticks (`) and allow embedded expressions with
${}. They also support multi-line strings.MCQ 15
What does
const { a, ...rest } = { a: 1, b: 2, c: 3 } give for rest?Answer: B
B is correct. The rest operator in object destructuring collects all remaining properties. Since
B is correct. The rest operator in object destructuring collects all remaining properties. Since
a is extracted separately, rest gets { b: 2, c: 3 }.MCQ 16
What is the output of
typeof NaN?Answer: C
C is correct. Despite standing for 'Not a Number',
C is correct. Despite standing for 'Not a Number',
NaN has type 'number' in JavaScript. Use isNaN() or Number.isNaN() to check for NaN.MCQ 17
What does the
... operator do in [...arr1, ...arr2]?Answer: B
B is correct. The spread operator expands both arrays into individual elements, creating a new merged array containing all elements from both.
B is correct. The spread operator expands both arrays into individual elements, creating a new merged array containing all elements from both.
MCQ 18
What is the value of
x after const [x = 5] = [undefined]?Answer: C
C is correct. Default values in destructuring are used when the value is
C is correct. Default values in destructuring are used when the value is
undefined. Since the array element is explicitly undefined, the default value 5 is used.MCQ 19
What is the difference between
Map and a regular object for key-value storage?Answer: B
B is correct. Regular object keys are coerced to strings. Map keys can be any type: numbers, booleans, objects, even other Maps. Maps also maintain insertion order and have a
B is correct. Regular object keys are coerced to strings. Map keys can be any type: numbers, booleans, objects, even other Maps. Maps also maintain insertion order and have a
size property.Coding Challenges
Challenge 1: Swap Values Using Destructuring
EasyGiven two variables a = 100 and b = 200, swap their values using array destructuring in one line. Do not use a temporary variable.
Sample Input
a = 100, b = 200
Sample Output
a = 200, b = 100
Must use destructuring. No temporary variable.
let a = 100;
let b = 200;
[a, b] = [b, a];
console.log("a =", a); // 200
console.log("b =", b); // 100Challenge 2: Remove Duplicates from Array
EasyWrite a function removeDuplicates(arr) that returns a new array with all duplicates removed. Use Set and spread.
Sample Input
[1, 2, 2, 3, 4, 4, 5]
Sample Output
[1, 2, 3, 4, 5]
Use Set and the spread operator. Return a new array.
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5]));
// [1, 2, 3, 4, 5]
console.log(removeDuplicates(["a", "b", "a", "c", "b"]));
// ["a", "b", "c"]Challenge 3: Deep Extract with Destructuring
MediumGiven the object below, use a single destructuring statement to extract the city name and the first hobby into separate variables.
Sample Input
{ user: { name: "Aarav", address: { city: "Delhi" }, hobbies: ["coding", "cricket"] } }
Sample Output
City: Delhi, First hobby: coding
Use one destructuring statement. No dot notation.
const data = {
user: {
name: "Aarav",
address: { city: "Delhi" },
hobbies: ["coding", "cricket"]
}
};
const { user: { address: { city }, hobbies: [firstHobby] } } = data;
console.log("City:", city); // Delhi
console.log("First hobby:", firstHobby); // codingChallenge 4: Merge Settings with Defaults
MediumWrite a function applySettings(userSettings) that merges user settings with defaults. Defaults: { theme: 'dark', fontSize: 14, language: 'en', notifications: true }. User settings should override defaults.
Sample Input
{ fontSize: 18, language: 'hi' }
Sample Output
{ theme: 'dark', fontSize: 18, language: 'hi', notifications: true }
Use the spread operator for merging. Return a new object.
const applySettings = (userSettings) => {
const defaults = { theme: 'dark', fontSize: 14, language: 'en', notifications: true };
return { ...defaults, ...userSettings };
};
console.log(applySettings({ fontSize: 18, language: 'hi' }));
// { theme: 'dark', fontSize: 18, language: 'hi', notifications: true }
console.log(applySettings({}));
// { theme: 'dark', fontSize: 14, language: 'en', notifications: true }Challenge 5: Safe Property Access Function
MediumWrite a function safeGet(obj, path, defaultValue) that uses optional chaining logic to safely access nested properties. The path is a dot-separated string like 'user.address.city'.
Sample Input
({ user: { name: "Aarav" } }, 'user.name', 'N/A')
Sample Output
Aarav
Split the path on dots and traverse. Use nullish coalescing for the default.
const safeGet = (obj, path, defaultValue = undefined) => {
const result = path.split('.').reduce((current, key) => current?.[key], obj);
return result ?? defaultValue;
};
const data = { user: { name: "Aarav", address: { city: "Delhi" } } };
console.log(safeGet(data, 'user.name', 'N/A')); // "Aarav"
console.log(safeGet(data, 'user.address.city', 'N/A')); // "Delhi"
console.log(safeGet(data, 'user.phone', 'N/A')); // "N/A"
console.log(safeGet(data, 'x.y.z', 'N/A')); // "N/A"Challenge 6: Word Frequency Counter with Map
MediumWrite a function wordFrequency(text) that returns a Map with each word (lowercase) as the key and its count as the value. Use a for...of loop.
Sample Input
"the cat sat on the mat the cat"
Sample Output
Map { 'the' => 3, 'cat' => 2, 'sat' => 1, 'on' => 1, 'mat' => 1 }
Use Map and for...of. Convert to lowercase.
const wordFrequency = (text) => {
const map = new Map();
const words = text.toLowerCase().split(/\s+/);
for (const word of words) {
if (word) {
map.set(word, (map.get(word) || 0) + 1);
}
}
return map;
};
const result = wordFrequency("the cat sat on the mat the cat");
result.forEach((count, word) => console.log(`${word}: ${count}`));
// the: 3, cat: 2, sat: 1, on: 1, mat: 1Challenge 7: Flexible Student Report Function
HardWrite a function generateReport that uses destructuring in parameters, default values, rest, and template literals. It takes a student object { name, age, ...scores } and returns a formatted report string.
Sample Input
{ name: "Priya", age: 15, maths: 90, science: 85, english: 92 }
Sample Output
Student: Priya (age 15)
Subjects: maths: 90, science: 85, english: 92
Average: 89
Use destructuring in parameters. Use rest to collect subject scores. Use template literals.
const generateReport = ({ name, age = "unknown", ...scores }) => {
const subjects = Object.entries(scores)
.map(([subject, score]) => `${subject}: ${score}`)
.join(", ");
const values = Object.values(scores);
const avg = Math.round(values.reduce((sum, v) => sum + v, 0) / values.length);
return `Student: ${name} (age ${age})\nSubjects: ${subjects}\nAverage: ${avg}`;
};
console.log(generateReport({ name: "Priya", age: 15, maths: 90, science: 85, english: 92 }));
console.log();
console.log(generateReport({ name: "Aarav", maths: 78, science: 82 }));Challenge 8: Array Utility Functions with ES6
HardWrite these utility functions using ES6 features: (1) unique(arr) using Set, (2) chunk(arr, size) using slice and a loop, (3) zip(arr1, arr2) that pairs elements, (4) flatten(arr) using spread and reduce.
Sample Input
Various arrays
Sample Output
unique: [1,2,3]
chunk: [[1,2],[3,4],[5]]
zip: [[1,'a'],[2,'b']]
flatten: [1,2,3,4,5,6]
Use arrow functions, spread, destructuring, and Set where appropriate.
const unique = arr => [...new Set(arr)];
const chunk = (arr, size) => {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
};
const zip = (a, b) => a.map((item, i) => [item, b[i]]);
const flatten = arr => arr.reduce((acc, item) =>
[...acc, ...(Array.isArray(item) ? item : [item])], []);
console.log(unique([1, 2, 2, 3, 3]));
console.log(chunk([1, 2, 3, 4, 5], 2));
console.log(zip([1, 2, 3], ['a', 'b', 'c']));
console.log(flatten([1, [2, 3], [4, 5], 6]));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