DEV Community

KISHAN RAMLAKHAN NISHAD
KISHAN RAMLAKHAN NISHAD

Posted on

Combined interview questions and answers focusing on forEach, map, filter, and reduce in JavaScript.

  1. What's the Difference Between forEach, map, filter, and reduce? When Should You Use Each?

Answer:

forEach():

Purpose: Executes a provided function once for each array element.
When to Use: When you need to perform side effects like logging or updating external variables but don't need to return a new array.
Returns: undefined (doesn't return a new array).
map():

Purpose: Creates a new array by applying a function to each element.
When to Use: When you need to transform each element and create a new array with the transformed data.
Returns: A new array with the same length.

filter():

Purpose: Creates a new array with elements that pass a provided test.
When to Use: When you need to select or filter elements based on a condition.
Returns: A new array with filtered elements (may have fewer elements).

reduce():

Purpose: Reduces the array to a single value by applying a function to each element and accumulating the result.
When to Use: When you need to aggregate values (e.g., sum, product, average).
Returns: A single value.
Enter fullscreen mode Exit fullscreen mode

2. Can You Give an Example Where You Would Use All Four Methods?
Answer:

Imagine you have an array of products, and you need to:

  1. Log all product names (forEach).
  2. Increase prices by 10% (map).
  3. Filter out products that cost more than $100 (filter).
  4. Calculate the total cost of the filtered products (reduce).
const products = [
  { name: "Laptop", price: 900 },
  { name: "Mouse", price: 25 },
  { name: "Keyboard", price: 45 },
  { name: "Monitor", price: 150 },
];

// 1. Log product names (forEach)
products.forEach(product => console.log(product.name));

// 2. Increase prices by 10% (map)
const updatedProducts = products.map(product => ({
  ...product,
  price: product.price * 1.1
}));

// 3. Filter products costing less than $100 (filter)
const affordableProducts = updatedProducts.filter(product => product.price < 100);

// 4. Calculate total cost of affordable products (reduce)
const totalCost = affordableProducts.reduce((sum, product) => sum + product.price, 0);

console.log(totalCost); // Output: Total cost of affordable products

Enter fullscreen mode Exit fullscreen mode

3. What Are the Key Differences Between map() and forEach()?
Answer:

Return Value:

  • map() returns a new array with transformed elements.
  • forEach() returns undefined; it is used for side effects.

Chaining:

  • You can chain map() with other array methods (like filter, reduce).
  • You cannot chain forEach() because it returns undefined.

When to Use:

  • Use map() when you need to transform data.
  • Use forEach() when you need to perform side effects like logging or modifying external variables.

4. Can You Chain map(), filter(), and reduce() Together?
Answer:

Yes, you can chain them to perform complex operations in a concise way.

Example: Find the total price of products costing less than $100 after applying a 20% discount.

const products = [
  { name: "Phone", price: 300 },
  { name: "Charger", price: 50 },
  { name: "Earphones", price: 70 },
  { name: "Laptop", price: 1000 },
];

// Chaining map, filter, and reduce
const total = products
  .map(product => ({ ...product, price: product.price * 0.8 })) // Apply 20% discount
  .filter(product => product.price < 100) // Filter products under $100
  .reduce((sum, product) => sum + product.price, 0); // Sum prices

console.log(total); // Output: 96 (Charger + Earphones after discount)

Enter fullscreen mode Exit fullscreen mode

5. How Does reduce() Work Internally? What Are accumulator and currentValue?
Answer:

  • accumulator: The accumulated result from the previous iteration. It starts with the initial value if provided.
  • currentValue: The current element being processed in the array.
const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0); // Initial value is 0

console.log(sum); // Output: 10

Enter fullscreen mode Exit fullscreen mode

These questions and answers will help you confidently explain and use these methods in your interview. Let me know if you need more advanced scenarios or additional concepts! 🚀

Top comments (0)