1. Basic Understanding
Question: What is the primary purpose of the map
method in JavaScript?
a) To filter elements based on a condition
b) To aggregate elements into a single value
c) To create a new array by applying a function to each element of the original array
d) To execute a function on each element without returning a new array
2. Practical Application
Question: Given the following code, what will be the output of squaredNumbers
?
const numbers = [2, 4, 6];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers);
a) [2, 4, 6]
b) [4, 16, 36]
c) [4, 8, 12]
d) [8, 16, 24]
3. Filtering Data
Question: How does the filter
method determine which elements to include in the new array?
a) It maps each element to a new value
b) It accumulates elements into a single value
c) It selects elements based on whether they pass a specified test function
d) It flattens nested arrays
4. Aggregating Data
Question: What does the following code snippet do?
const numbers = [1, 2, 3, 4, 5];
const product = numbers.reduce((acc, num) => acc * num, 1);
console.log(product);
a) Calculates the sum of the numbers
b) Calculates the product of the numbers
c) Finds the maximum number
d) Finds the average of the numbers
5. Combining Methods
Question: What is the result of the following code?
const items = [
{ name: 'Pen', quantity: 10 },
{ name: 'Notebook', quantity: 5 },
{ name: 'Eraser', quantity: 8 }
];
const itemDescriptions = items
.filter(item => item.quantity > 5)
.map(item => `${item.name} (Quantity: ${item.quantity})`);
console.log(itemDescriptions);
a) [‘Pen (Quantity: 10)’, ‘Notebook (Quantity: 5)’, ‘Eraser (Quantity: 8)’]
b) [‘Pen (Quantity: 10)’, ‘Eraser (Quantity: 8)’]
c) [‘Pen’, ‘Eraser’]
d) [‘Notebook (Quantity: 5)’]
6. Using flatMap
Question: What will be the output of the following code?
const phrases = [
'Learn JavaScript',
'Transform Data'
];
const words = phrases.flatMap(phrase => phrase.split(' '));
console.log(words);
a) [‘Learn’, ‘JavaScript’, ‘Transform’, ‘Data’]
b) [‘Learn JavaScript’, ‘Transform Data’]
c) [‘Learn’, ‘JavaScript’]
d) [‘Transform’, ‘Data’]
Answers
- c) To create a new array by applying a function to each element of the original array
- b) [4, 16, 36]
- c) It selects elements based on whether they pass a specified test function
- b) Calculates the product of the numbers
- b) [‘Pen (Quantity: 10)’, ‘Eraser (Quantity: 8)’]
- a) [‘Learn’, ‘JavaScript’, ‘Transform’, ‘Data’]
How did you do? Let me know if you’d like explanations for any of the answers or if you need further practice!