Learn JavaScript - Iterators Cheatsheet - Codecademy
Learn JavaScript - Iterators Cheatsheet - Codecademy
Iterators
The .reduce() method iterates through an array const arrayOfNumbers = [1, 2, 3, 4];
and returns a single value.
In the above code example, the .reduce() method
will sum up all the elements of the array. It takes a const sum =
callback function with two parameters arrayOfNumbers.reduce((accumulator,
(accumulator, currentValue) as currentValue) => {
arguments. On each iteration, accumulator is the
value returned by the last iteration, and the return accumulator + currentValue;
currentValue is the current element. Optionally, a });
second argument can be passed which acts as the initial
value of the accumulator.
console.log(sum); // 10
The .forEach() method executes a callback const numbers = [28, 77, 45, 99, 27];
function on each of the elements in an array in order.
In the above example code, the callback function
containing a console.log() method will be numbers.forEach(number => {
executed 5 times, once for each element. console.log(number);
});
The .filter() method executes a callback function const randomNumbers = [4, 11, 42, 14, 39];
on each element in an array. The callback function for
const filteredArray =
each of the elements must return either true or
false . The returned array is a new array with any randomNumbers.filter(n => {
elements for which the callback function returns true . return n > 5;
In the above code example, the array
});
filteredArray will contain all the elements of
randomNumbers but 4 .
The .map() Method
console.log(announcements);
In JavaScript, functions are a data type just as strings, let plusFive = (number) => {
numbers, and arrays are data types. Therefore, functions
return number + 5;
can be assigned as values to variables, but are different
from all other data types because they can be invoked. };
// f is assigned the value of plusFive
let f = plusFive;
plusFive(3); // 8
// Since f has a function value, it can be
invoked.
f(9); // 14
Callback Functions
Higher-Order Functions
Print Share