Let’s Talk about JavaScript’s Higher-Order Functions — Pt. 1

.map, .filter, and .reduce explained with emojis

.filter()

Definition + Syntax — MDN

/* 
Definition
:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
*/
// Syntax:
let newArray = arr.filter(callback(currentValue[, index[, array]]) {
// return element for newArray, if true
}[, thisArg]);

When to Use:

In Action:

Input: "abracadabra"
Expected Output:
5
const vowels = ['a', 'e', 'i', 'o', 'u']const getVowelCount = (word) => {
let vowelsCount = 0;
let splitWord = Array.from(word)

splitWord.filter(letter => {
vowels.includes(letter)
? vowelsCount++
: null
});

return vowelsCount;
}
const getVowelCount = (word) => {
let vowelCount = 0;
let vowels = ['a', 'e', 'i', 'o', 'u'];
for (let i = 0; i < word.length; i++) {
for (let j = 0; j < vowels.length; j++) {
if (word[i] === vowels[j]) {
vowelCount++;
}
}
}
return vowelCount;
}

.map()

Definition + Syntax — MDN

/* 
Definition
:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
*/
// Syntax:
let newArray = arr.map(callback(currentValue[, index[, array]]) {
// return element for newArray, after executing something
}[, thisArg]);

When to Use:

In Action:

const alphabet = [...new Array(26).keys()]
.map(i => String.fromCharCode(i + 97))
[...new Array(26)] => 
[
undefined, undefined, undefined,
undefined, undefined, undefined,
undefined, undefined, undefined,
undefined, undefined, undefined,
undefined, undefined, undefined,
undefined, undefined, undefined,
undefined, undefined, undefined,
undefined, undefined, undefined,
undefined, undefined
]
[...new Array(26).keys()] =>
[
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25
]
.map(i => String.fromCharCode(i + 97)) =>
[
'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x',
'y', 'z'
]
function setAlphaIndex() {
let alphaIndex = [];
for (let i = 0; i < 26; i++) {
alphaIndex.push(i)
}
return alphaIndex;
}
function getLowecaseAlphabet() {
let alphabet = [];
let alphaIncrements = setAlphaIndex();
for (let i = 0; i < alphaIncrements.length; i++) {
let letter = String.fromCharCode(i + 97)
alphabet.push(letter)
}
return alphabet
}

Full stack web developer. Frontend and design enthusiast. Avid rock climber and amateur photographer.