Functions: Higher-Order Flashcards

1
Q

What is a higher-order function (HOF)?

A

It’s a function that takes one or more functions as arguments, and/or returns a function as its result.

HOF are a powerful feature that allow to abstract over common patterns and to create reusable code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the map() method?

A

Its a higher-order function (HOF) that creates a new array by calling a provided function on each element of an existing array.

The provided function takes the current element as its argument and returns a new value, which is used to populate the new array.

It does not modify the original array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the reduce() method?

A

It’s a higher-order function (HOF) that applies a provided function to each element of an array in order to reduce the array to a single value.

It takes 2 arguments: acc, curr
Returns a new accumulator value.

Good for summing, counting occurrences of elements, and finding the maximum or minimum value in an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between filter() and find() methods?

A

Both are higher-order functions (HOF) that operate on arrays.
filter() creates a new array containing all elements that pass a provided test function.
find() returns the value of the first element in an array that passes a provided test function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a pure function?

A

It’s a function that always returns the same output for a given input, and does not have any side effects like modifying its arguments or the global state.

Pure functions are a key concept in functional programming, and have benefits like:
- improved testability,
- easier debugging,
- reduced complexity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a higher-order function?

A

a function that takes another function as an argument, or returns a function as a result

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?

A

forEach:

  • Iterates through the elements in an array.
  • Executes a callback for each element.
  • Does not return a value.

map():

  • Iterates through the elements in an array.
  • “Maps” each element to a new element by calling the function on each element, creating a new array as a result.

The main difference between .forEach and .map() is that .map() returns a new array. If you need the result, but do not wish to mutate the original array, .map() is the clear choice. If you simply need to iterate over an array, forEach is a fine choice.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly