If you would like to test your understanding of map
and forEach
with a few quiz questions, here are few.
Quiz
1. Basic Understanding
Question: What is the primary difference between the map
and forEach
methods in JavaScript?
a) map
modifies the original array, while forEach
creates a new array.
b) forEach
returns a new array, while map
does not return anything.
c) map
returns a new array with transformed values, while forEach
performs operations without creating a new array.
d) map
can only be used on objects, while forEach
can be used on arrays.
2. Practical Application
Question: Given the following code, what will be the output?
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
doubled.forEach(num => console.log(num));
a) 1, 2, 3, 4, 5
b) 2, 4, 6, 8, 10
c) [2, 4, 6, 8, 10]
d) 2 2 4 4 6 6 8 8 10 10
3. Side Effects
Question: Which method would you use if you need to perform an operation that doesn’t require the creation of a new array, such as logging each element to the console?
a) map
b) forEach
c) Both map
and forEach
d) Neither map
nor forEach
4. Performance
Question: If you are concerned about performance and need to perform an operation on each array element without creating a new array, which method is generally more efficient?
a) map
b) forEach
c) Both are equally efficient
d) It depends on the size of the array
5. Coding Challenge
Question: Consider the following code snippet. What will be the output of the agesNextYear
variable?
const users = [
{ name: 'Alice', age: 12 },
{ name: 'Bob', age: 18 },
{ name: 'Charlie', age: 20 }
];
const agesNextYear = users.map(user => user.age + 1);
console.log(agesNextYear);
a) [12, 18, 20]
b) [13, 19, 21]
c) [13, 18, 21]
d) [12, 19, 20]
6. Use Case
Question: Which method is better suited for transforming each element of an array and generating a new array from these transformations?
a) map
b) forEach
c) filter
d) reduce
Answers
- c)
map
returns a new array with transformed values, whileforEach
performs operations without creating a new array. - b) 2, 4, 6, 8, 10
- b)
forEach
- b)
forEach
- b) [13, 19, 21]
- a)
map
How did you do? Let me know if you’d like explanations for any of the answers or if you have more questions!