Functional programming is a hot topic in JavaScript interviews. Hiring managers want to see that you can write clean, predictable, and maintainable code. Mastering the array methods map, filter, and reduce is a fantastic way to demonstrate these skills. Let's dive into some common interview questions that will test your understanding of these powerful tools.
1. What's the fundamental difference between map, filter, and reduce?
Key Concept: This question assesses your high-level understanding of the purpose of each method.
Standard Answer: The fundamental difference lies in what they do and what they return.
maptransforms each element in an array and returns a new array of the same length with the transformed elements. Think of it as creating a one-to-one mapping from the original array to a new one.
CODEconst numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // [2, 4, 6]
filtercreates a new array containing only the elements that pass a specific condition. The new array's length can be less than or equal to the original array's length.
CODEconst numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]
reduceiterates over an array and returns a single value. This value is the result of a "reducer" function that accumulates a value from each element.
CODEconst numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0); // 15
Possible 3 Follow-up Questions: 👉 ()
- Why is it generally not a good idea to modify the
Array.prototypedirectly in a production application? - How would you add support for the
thisArgparameter that the nativemapmethod has? - What are the potential performance implications of your implementation compared to the native one?
3. How would you use filter to remove all falsy values from an array?
Key Concept: This question checks your knowledge of truthy and falsy values in JavaScript and how to apply that to filter.
Standard Answer: A concise way to do this is to pass the Boolean constructor directly to the filter method.
const mixedArr = [0, 1, false, 2, '', 3, null, 'a', undefined, NaN];
const truthyArr = mixedArr.filter(Boolean); // [1, 2, 3, 'a']
The filter method calls the Boolean constructor for each element. The constructor coerces each element to its boolean equivalent, and filter keeps only the ones that are true.
Possible 3 Follow-up Questions: 👉 ()
- What happens if you don't provide an
initialValuetoreduce? - Can you provide an example of when
currentIndexandarraymight be useful? - How would you use
reduceto flatten an array of arrays?
5. You have an array of objects. How would you use map and filter together to get the names of all users who are over 18?
Key Concept: This tests your ability to chain these methods to perform more complex data transformations.
Standard Answer: I would first use filter to get an array of users who are over 18, and then I would chain map to that result to extract just their names.
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 32 },
{ name: 'David', age: 16 }
];
const adultNames = users
.filter(user => user.age > 18)
.map(user => user.name); // ['Alice', 'Charlie']```
{% endraw %}
This is a very common and readable pattern in functional programming.
**Possible 3 Follow-up Questions:** 👉 ([Want to test your skills? Try a Mock Interview — each question comes with real-time voice insights](https://offereasy.ai))
1. Could this be achieved with a single {% raw %}`reduce`{% endraw %}? If so, which approach would you prefer and why?
2. What are the performance considerations when chaining multiple array methods?
3. How would you handle a situation where the {% raw %}`age`{% endraw %} property might be missing on some user objects?
***
## 6. How can you use {% raw %}`reduce`{% endraw %} to group an array of objects by a specific property?
**Key Concept:** This is a more advanced {% raw %}`reduce`{% endraw %} question that demonstrates your ability to use it for more than just simple accumulations.
**Standard Answer:** You can use {% raw %}`reduce`{% endraw %} to transform an array into an object. The accumulator, in this case, would be the object you're building.
{% raw %}
```javascript
const people = [
{ name: 'Alice', city: 'New York' },
{ name: 'Bob', city: 'London' },
{ name: 'Charlie', city: 'New York' }
];
const peopleByCity = people.reduce((acc, person) => {
const city = person.city;
if (!acc[city]) {
acc[city] = [];
}
acc[city].push(person);
return acc;
}, {});
/*
Result:
{
'New York': [ { name: 'Alice', city: 'New York' }, { name: 'Charlie', city: 'New York' } ],
'London': [ { name: 'Bob', city: 'London' } ]
}
*/
Possible 3 Follow-up Questions: 👉 ()
- How would you modify the code to get the final array of data?
- What are the potential drawbacks of firing off multiple network requests like this in parallel?
- How would
forEachbehave differently with anasynccallback compared tomap?
8. Can you use map or filter on an object?
Key Concept: This question probes your understanding of what data types these methods are designed for.
Standard Answer: map and filter are methods on the Array.prototype, so they can't be directly used on an object. However, you can use them on the keys, values, or entries of an object by first converting them into an array using Object.keys(), Object.values(), or Object.entries().
const myObj = { a: 1, b: 2, c: 3 };
// Map over the values and double them
const doubledValues = Object.values(myObj).map(value => value * 2); // [2, 4, 6]
// Filter out key-value pairs where the value is not even
const evenEntries = Object.entries(myObj).filter(([key, value]) => value % 2 === 0);
// [['b', 2]]```
{% endraw %}
**Possible 3 Follow-up Questions:** 👉 ([Want to test your skills? Try a Mock Interview — each question comes with real-time voice insights](https://offereasy.ai))
1. How would you convert the {% raw %}`evenEntries`{% endraw %} array back into an object?
2. Are there any performance implications to be aware of when converting an object to an array and back?
3. Can you describe a scenario where you would prefer to use a {% raw %}`for...in`{% endraw %} loop over these methods for an object?
***
## 9. When would you prefer using {% raw %}`reduce`{% endraw %} over a combination of {% raw %}`map`{% endraw %} and {% raw %}`filter`{% endraw %}?
**Key Concept:** This question assesses your ability to reason about code efficiency and readability.
**Standard Answer:** You might prefer {% raw %}`reduce`{% endraw %} when you need to perform both a mapping and a filtering operation in a single pass. This can be more efficient as it avoids creating an intermediate array that the {% raw %}`filter`{% endraw %} and {% raw %}`map`{% endraw %} chain would produce.
For example, to get the sum of the squares of all even numbers:
{% raw %}
```javascript
const numbers = [1, 2, 3, 4, 5];
// Using map and filter
const sumOfSquaresOfEvens = numbers
.filter(num => num % 2 === 0)
.map(num => num * num)
.reduce((acc, num) => acc + num, 0); // 20
// Using a single reduce
const sumWithReduce = numbers.reduce((acc, num) => {
if (num % 2 === 0) {
return acc + (num * num);
}
return acc;
}, 0); // 20
While the single reduce is more performant, the chained map and filter approach can often be more readable. The choice depends on the specific use case and a balance between performance and clarity.
Possible 3 Follow-up Questions: 👉 ()
- Can you give an example of an impure function that you could pass to one of these methods? What would be the potential problems with that?
- What is function composition, and how can it be used with these methods?
- Besides
map,filter, andreduce, what are some other array methods in JavaScript that align with functional programming principles?
SOCIAL SHARE CARD GENERATOR