Learn JavaScript - Iterators Cheatsheet - Codecademy
Learn JavaScript - Iterators Cheatsheet - Codecademy
Iterators
The .reduce() method iterates through an array and const arrayOfNumbers = [1, 2, 3, 4];
returns a single value.
In the above code example, the .reduce() method will
sum up all the elements of the array. It takes a callback const sum =
function with two parameters (accumulator, arrayOfNumbers.reduce((accumulator,
currentValue) as arguments. On each iteration, currentValue) => {
accumulator is the value returned by the last iteration,
return accumulator + currentValue;
and the 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 function on const numbers = [28, 77, 45, 99, 27];
each of the elements in an array in order.
In the above example code, the callback function
containing a console.log() method will be executed 5 numbers.forEach(number => {
times, once for each element. console.log(number);
});
The .filter() method executes a callback function on const randomNumbers = [4, 11, 42, 14, 39];
each element in an array. The callback function for each
const filteredArray =
of the elements must return either true or false . The
returned array is a new array with any elements for which randomNumbers.filter(n => {
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 .
https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-iterators/cheatsheet 1/4
1/18/24, 10:43 AM Learn JavaScript: Iterators Cheatsheet | Codecademy
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
https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-iterators/cheatsheet 2/4
1/18/24, 10:43 AM Learn JavaScript: Iterators Cheatsheet | Codecademy
Callback Functions
Higher-Order Functions
https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-iterators/cheatsheet 3/4
1/18/24, 10:43 AM Learn JavaScript: Iterators Cheatsheet | Codecademy
Print Share
https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-iterators/cheatsheet 4/4