Learn JavaScript - Iterators Cheatsheet - Codecademy
Learn JavaScript - Iterators Cheatsheet - Codecademy
Iterators
In JavaScript, functions are a data type just as strings, let plusFive = (number) => {
numbers, and arrays are data types. Therefore,
return number + 5;
functions 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
https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-iterators/cheatsheet 1/4
15/11/2023 19:12 Learn JavaScript: Iterators Cheatsheet | Codecademy
Higher-Order Functions
They can be passed as arguments and returned //Re-assign the function to a new
from other functions. variable newFunc
They can be assigned to variables, array const newFunc = originalFunc;
elements, and other objects.
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 const numbers = [28, 77, 45, 99, 27];
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 executed numbers.forEach(number => {
5 times, once for each element. console.log(number);
});
The .filter() method executes a callback function on const randomNumbers = [4, 11, 42, 14,
each element in an array. The callback function for
39];
each of the elements must return either true or
false . The returned array is a new array with any const filteredArray =
elements for which the callback function returns true . randomNumbers.filter(n => {
In the above code example, the array filteredArray return n > 5;
will contain all the elements of randomNumbers but 4 .
});
https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-iterators/cheatsheet 3/4
15/11/2023 19:12 Learn JavaScript: Iterators Cheatsheet | Codecademy
console.log(announcements);
Print Share
https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-iterators/cheatsheet 4/4