We'll look at the array methods that allow us to test and transform arrays more simply and consistently.
By the end of this lesson, students should be able to:
- Write callbacks to pass to array methods
- Write functions to emulate array methods
- Write functions using array methods to add functionality.
We'll explore and implement proxies for a variety of the JavaScript Array methods.
A callback is a function that gets passed into an initial function/method as an argument, so that the initial function/method can invoke it.
We'll also be working with arrow
(sometimes referred to as fat arrow
) functions versus standard function declarations.
Arrow functions:
- always have a bound
this
- cannot be used as a Constructor (no
new
, noprototypes
) - no
arguments
> typeof () => {}
'function'
> () => {} instanceof Function
true
- The forEach method iterates over all of the elements in an array.
- Unlike a
for
loop,forEach
cannot be stopped or broken out of - Does not change the elements of the original array and will return
undefined
- The map method returns a new array with the results of the functions applied to the array it is called upon
- The array it is called upon therefore is not mutated
Write a function, mutate
, that takes an array and a function as arguments and *does change the original array based on the return value of invoking transform
.
const mutate = function(array, transform) {
};
- The reduce method returns a single value from operating on all the values in the array. It "reduces" many to one.
- The original array
reduce
is invoked on does not change.
- The every method checks to see if all elements of an array meet some test. The function used for this should only return
true
orfalse
. This type of function is often called a predicate.
Research the some and filter methods as they are also useful.
- What is the purpose of each?
- What is returned from each?
- Is the array they are called upon mutated?
Source code distributed under the MIT license. Text and other assets copyright General Assembly, Inc., all rights reserved.