• Stars
    star
    111
  • Rank 314,510 (Top 7 %)
  • Language
    JavaScript
  • Created over 4 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A complete summary of functional programming in JavaScript

Functional Programming in JavaScript

Twitter Follow
Author: Asabeneh Yetayeh

Support Asabeneh to create more educational materials

Functional Programming

In this article, I will try to help you to have a very good understanding of the most common feature of JavaScript, functional programming.

Functional programming allows you to write shorter code, clean code, and also to solve complicated problems which might be difficult to solve in a traditional way.

For more JavaScript and other programming lessons and tutorials, you may check Washera YouTube channel.

In this article we will cover all JS functional programming methods:

  • forEach
  • map
  • filter
  • reduce
  • find
  • findIndex
  • some
  • every

1. forEach

We use forEach when we like to iterate through an array of items. The forEach is a higher-order function and it takes call-back as a parameter. The forEach method is used only with array and we use forEach if you are interested in each item or index or both.

// syntax in a normal or a function declaration

function callback(item, index, arr) {}
array.forEach(callback)

// or syntax in an arrow function
const callback = (item, i, arr) => {}
array.forEach(callback) 

The call back function could be a function declaration or an arrow function.

Let see different examples

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway']
countries.forEach(function(country, index, arr) {
  console.log(i, country.toUpperCase())
})

If there is no much code inside the code block we can use an arrow function and we can write it without a curly bracket. The index and the array parameters are optional, we can omit them.

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway']
countries.forEach((country, i) => console.log(i, country.toUpperCase()))
0 "FINLAND"
1 "ESTONIA"
2 "SWEDEN"
3 "NORWAY"

For example if we like to change each country to uppercase and store it back to an array we write it as follows.

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway']
const newCountries = []
countries.forEach(country => newCountries.push(country))

console.log(newCountries) // ["Finland", "Estonia", "Sweden", "Norway"]

Let us see more examples. For instance if we want to sum an array of numbers we can use forEach or reduce. Let us see how we use forEach to sum all numbers in an array.

const numbers = [1, 2, 3, 4, 5]
let sum = 0
numbers.forEach((n) => sum += n)

console.log(sum) // 15

Let us move to the next functional programming method which is going to be a map.

2. map

We use the map method whenever we like to modify an array. We use the map method only with arrays and it always returns an array.

// syntax in a normal or a function declaration

function callback(item, i) {
return // code goes here
}

const modifiedArray = array.map(callback)

// or syntax in an arrow function

const callback = (item, i) => {
return // code goes here
}
const modifiedArray = array.map(callback)

Now, let us modify the countries array using the map method. The index is an optional parameter

// Using function declaration

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway']

const newCountries = countries.map(function(country) {
return country.toUpperCase()
})

console.log(newCountries)

// map using an arrow function call back

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway']
const newCountries = countries.map(country => country.toUpperCase())

console.log(newCountries) // ["FINLAND", "ESTONIA", "SWEDEN", "NORWAY"]

As you can see that map is very handy to modify an array and to get an array back. Now, let us create an array of the length of the countries from the countries array.

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway']
const countriesLength = countries.map(country => country.length)

console.log(countriesLength) // [7, 7, 6, 6]

Let us see another more example

const numbers = [1, 2, 3, 4, 5]
const squares = numbers.map(n => n ** 2)

console.log(squares) // [1, 4, 9, 16, 25]

3. filter

As you may understand from the literal meaning of filter, it filters out items based on some criteria. The filter method like forEach and map is used with an array and it returns an array of the filtered items.

For instance if we want to filter out countries containing a substring land from an array of countries. See the example below:

// syntax in a normal or a function declaration
function callback(item) {
  return // boolean
}

const filteredArray = array.filter(callback)

// or syntax in an arrow function

const callback = (item) => {
  return // boolean
}
const filteredArray = array.filter(callback)
const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland']
const countriesWithLand = countries.filter(country => country.includes('land'))
console.log(countriesWithLand) // ["Finland", "Iceland"]

How about if we want to filter out countries not containing the substring land. We use negation to achieve that.

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland']
const countriesWithLand = countries.filter(country => !country.includes('land'))
console.log(countriesWithLand) // ["Estonia", "Sweden", "Norway"]

Let's see an additional example about the filter, let us filter even or odd numbers from an array of numbers

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const evens = numbers.filter(n => n % 2 === 0)
const odds = numbers.filter(n => n % 2 !== 0)
console.log(evens) // [0, 2, 4, 6, 8, 10]
console.log(odds) // [1, 3, 5, 7, 9]

Now, you know how to filter let us move on to the next functional programming, reduce.

4. reduce

Like forEach, map, and filter, reduce is also used with an array and it returns a single value. You can associate reduce with a blender. You put different fruits to a blend and you get a mix of fruit juice. The juice is the output from the reduction process.

We use the reduce method to sum all numbers in an array together, or to multiply items in an array or to concatenate items in an array. Let us see the following different example to make this explanation more clear.

// syntax in a normal or a function declaration

function callback(acc, cur) {
    return // code goes here
}

const reduced = array.reduce(callback, optionalInitialValue)

// or syntax in an arrow function

const reduced =  callback(acc, cur) => {
    return // code goes here
}
const reduced = array.reduce(callback)

The default initial value is 0. We can change the initial value if we want to change it.

For instance if we want to add all items in an array and if all the items are numbers we can use reduce.

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const sum = numbers.reduce((acc, cur) => acc + cur)
console.log(sum) // 55

Reduce has a default initial value which is zero. Now, let us use a different initial value which is 5 in this case.

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const sum = numbers.reduce((acc, cur) => acc + cur, 5)
console.log(sum) // 60

Let us concatenate strings using reduce

const strs = ['Hello', 'world', '!']
const helloWorld = strs.reduce((acc, cur) => acc + ' '+  cur)
console.log(helloWorld) // "Hello world !"

We can multiply items of an array using reduce and we will return the value.

const numbers = [1, 2, 3, 4, 5]
const value = numbers.reduce((acc, cur) => acc * cur)
console.log(value) // 120

Let us try it with an initial value

const numbers = [1, 2, 3, 4, 5]
const value = numbers.reduce((acc, cur) => acc * cur, 10)
console.log(value) // 1200

5. find

If we are interested in the first occurrence of a certain item or element in an array we can use find method. Unlike map and filter, find just return the first occurrence of an item instead of an array.

// syntax in a normal or a function declaration

function callback(item) {
return // code goes here
}

const item = array.find(callback)

// or syntax in an arrow function

const reduced =  callback(item) => {
return // code goes here
}
const item = array.find(callback)

Let find the first even number and the first odd number in the numbers array.

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const firstEvenNum = numbers.find((n) => n % 2 === 0)
const firstOddNum = numbers.find((n) => n % 2 !== 0)
console.log(firstEvenNum)  // 0
console.log(firstOddNum)   // 1

Let us find the first country which contains a substring way

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland']
const countryWithWay= countries.find((country) => country.includes('way'))
console.log(countriesWithWay) // Norway

Let us find the first country which has only six characters

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland']
const sixCharsCountry = countries.find((country) => country.length === 6)
console.log(sixCharsCountry) // Sweden

Let us find the first country in the array which has the letter 'o'

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland']
const index = countries.find((country) => country.includes('o'))
console.log(index // Estonia

6. findIndex

The findIndex method works like find but findIndex returns the index of the item. If we are interested in the index of a certain item or element in an array we can use findIndex. The findIndex return the index of the first occurrence of an item.

// syntax in a normal or a function declaration

function callback(item) {
return // code goes here
}

const index = array.findIndex(callback)

// or syntax in an arrow function

const reduced =  callback(item) => {
return // code goes here
}
const index = array.findIndex(callback)

Let us find the index of the first even number and the index of the first odd number in the numbers array.

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const firstEvenIndex = numbers.findIndex((n) => n % 2 === 0)
const firstOddIndex = numbers.findIndex((n) => n % 2 !== 0)
console.log(firstEvenIndex)  // 0
console.log(firstOddIndex)   // 1

Let us find the index of the first country in the array which has exactly six characters

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland']
const index = countries.findIndex((country) => country.length === 6)
console.log(index //2

Let us find the index of the first country in the array which has the letter 'o'.

const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland']
const index = countries.findIndex((country) => country.includes('o'))
console.log(index // 1

Let us move on to the next functional programming, some.

7. some

The some method is used with array and return a boolean. If one or some of the items satisfy the criteria the result will be true else it will be false. Let us see it with an example.

In the following array some numbers are even and some are odd, so if I ask you a question, are there even numbers in the array then your answer will be yes. If I ask you also another question, are there odd numbers in the array then your answer will be yes. On the contrary, if I ask you, are all the numbers even or odd then your answer will be no because all the numbers are not even or odd.

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const someAreEvens = numbers.some((n) => n % 2 === 0)
const someAreOdds = numbers.some((n) => n % 2 !== 0)
console.log(someAreEvens) // true
console.log(someAreOdds)  // true

Let us another example

const evens = [0, 2, 4, 6, 8, 10]
const someAreEvens = evens.some((n) => n % 2 === 0)
const someAreOdds = evens.some((n) => n % 2 !== 0)
console.log(someAreEvens) // true
console.log(someAreOdds)  // false

Now, let us see one more functional programming, every.

8. every

The method every is somehow similar to some but every item must satisfy the criteria. The method every like some returns a boolean.

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const allAreEvens = numbers.every((n) => n % 2 === 0)
const allAreOdd s= numbers.every((n) => n % 2 !== 0)

console.log(allAreEven) // false
console.log(allAreOdd)  // false

const evens = [0, 2, 4, 6, 8, 10]
const someAreEvens = evens.some((n) => n % 2 === 0)
const someAreOdds = evens.some((n) => n % 2 !== 0)

console.log(someAreEvens) // true
console.log(someAreOdds)  // false

Exercise

const products = [
  { product: 'banana', price: 3 },
  { product: 'mango', price: 6 },
  { product: 'potato', price: ' ' },
  { product: 'avocado', price: 8 },
  { product: 'coffee', price: 10 },
  { product: 'tea', price: '' }
]
  1. Print the price of each product using forEach

  2. Print the product items as follows using forEach

    The price of banana is 3 euros.
    The price of mango is 6 euros.
    The price of potato is unknown.
    The price of avocado is 8 euros.
    The price of coffee is 10 euros.
    The price of tea is unknown.
  3. Calculate the sum of all the prices using forEach

  4. Create an array of prices using map and store it in a variable prices

  5. Filter products with prices

  6. Use method chaining to get the sum of the prices(map, filter, reduce)

  7. Calculate the sum of all the prices using reduce only

  8. Find the first product which doesn't have a price value

  9. Find the index of the first product which does not have price value

  10. Check if some products do not have a price value

  11. Check if all the products have price value

  12. Explain the difference between forEach, map, filter and reduce

  13. Explain the difference between filter, find and findIndex

  14. Explain the difference between some and every

More Materials

If you want to dive deep into JavaScript, you can give it a try to the 30DaysOfJavaScript challenge. This challenge will take quite long time to finish but you can get all you need about JavaScript

JavaScript

  1. 30DaysJavaScript challenge
  2. JavaScript for Everyone
  3. JavaScript Loops
  4. Destructuring in JavaScript

React

  1. React for Everyone

Python

  1. 30DaysOfPython

🎉 CONGRATULATIONS 🎉

Now, you know everything you need to know about JavaScript functional programming methods.

More Repositories

1

30-Days-Of-JavaScript

30 days of JavaScript programming challenge is a step-by-step guide to learn JavaScript programming language in 30 days. This challenge may take more than 100 days, please just follow your own pace. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
JavaScript
43,077
star
2

30-Days-Of-Python

30 days of Python programming challenge is a step-by-step guide to learn the Python programming language in 30 days. This challenge may take more than100 days, follow your own pace. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
Python
42,171
star
3

30-Days-Of-React

30 Days of React challenge is a step by step guide to learn React in 30 days. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
JavaScript
25,696
star
4

10-days-of-git-and-github

Some video lessons on YouTube: This videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
HTML
1,378
star
5

30-Days-Of-HTML

A step by step guide to learn the concept of HTML, DOM tree, and web development in 30 days. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
HTML
1,228
star
6

JavaScript-for-Everyone

A step by step guide to learn JavaScript and programming. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
JavaScript
1,095
star
7

React-For-Everyone

A step by step guide to learn and master react.js
JavaScript
476
star
8

asabeneh

442
star
9

Python-for-Everyone

A step by step guide to learn Python Programming
Jupyter Notebook
221
star
10

HTML-CSS-Website-Template

HTML-CSS-Website-Template
HTML
104
star
11

Git-and-Github

Basics of Git and Github
102
star
12

30-Days-Of-Go

97
star
13

30DaysOfSQL

94
star
14

JavaScript-Loops

A complete summary of loops in JavaScript
JavaScript
67
star
15

30DaysOfTypeScript

65
star
16

10DaysOfPython

Python
63
star
17

Destructuring-in-JavaScript

A complete summary of destructuring in JavaScript
43
star
18

data-analysis-with-python-summer-2021

Jupyter Notebook
43
star
19

advanced-python-march-2022

Jupyter Notebook
39
star
20

Python-and-SQL

38
star
21

NumPy

Jupyter Notebook
37
star
22

Pandas

HTML
35
star
23

fundamental-python-march-2022

Python
35
star
24

30-Days-Of-CSS

29
star
25

advanced-python-autumn-2021

Python
27
star
26

git-practice

HTML
27
star
27

mern-stack-app-2019

JavaScript
26
star
28

AI-with-Python

26
star
29

react-time-of-day

A simple react project
JavaScript
26
star
30

How-to-deploy-Node-project-on-heroku

A step-by-step guide to deploy a node application on Heroku.
HTML
26
star
31

python-autumn-2024

A Python programming course at Omnia, Fall 2024
Python
22
star
32

python-autumn-2023

Python
21
star
33

python-spring-2024

Python
21
star
34

Fundamentals-of-python-august-2021

Python
20
star
35

python-autumn-2022

Python
20
star
36

data-science-for-everyone

Jupyter Notebook
20
star
37

python-projects

19
star
38

static-website

HTML
19
star
39

git-lesson-fullstack-bootcamp

This is just to teach Git and GitHub
HTML
19
star
40

fundamentals-of-python-Nov-Dec-2021

Python
19
star
41

redux-lesson-2020

JavaScript
18
star
42

webTools

WebTools is a simple JavaScript module which increases productivity
JavaScript
18
star
43

react-form-with-hooks

JavaScript
18
star
44

git-lesson-2023

Python
17
star
45

matplotlib

Jupyter Notebook
17
star
46

redux-lesson

JavaScript
17
star
47

git-lessons

HTML
16
star
48

world-countries-data-api

World Countries Data
JavaScript
16
star
49

react-redux-boilerplate-2019

JavaScript
15
star
50

express-app

Node, Express and MongoDB fullstack application
HTML
15
star
51

react-students

JavaScript
14
star
52

JavaScript-spring-2021

JavaScript
14
star
53

HTML-CSS-Winter-2021

HTML
14
star
54

react-starter-2020

JavaScript
14
star
55

git-github-lesson

14
star
56

express-node-api

HTML
13
star
57

JavaScript-String-Interpolation

JavaScript
12
star
58

world-countries-data

World Countries Data
JavaScript
12
star
59

react-spring-2021

HTML
11
star
60

node-lesson-2019

JavaScript
11
star
61

charts

This application creates charts or graphs using HTML, CSS and JavaScript
JavaScript
10
star
62

ML-project

10
star
63

react-revsion-may-06

JavaScript
10
star
64

python-winter-2021

Jupyter Notebook
9
star
65

The-Complete-HTML5-Guide

HTML
8
star
66

python-spring-2021

Jupyter Notebook
8
star
67

HTMLCSS-Spring-2021

HTML
7
star
68

Java

Java
7
star
69

data-visualization

Jupyter Notebook
6
star
70

JavaScript-autumn-2020

JavaScript
6
star
71

Angular

TypeScript
6
star
72

web-dev-autumn-2024

HTML
6
star
73

github-slideshow

A robot powered training repository 🤖
HTML
6
star
74

washera-static-website

A sample static website to teach beginners HTML and CSS
HTML
6
star
75

data-analysis-with-python-autumn-2024

Python
6
star
76

mern-stack

JavaScript
5
star
77

Introduction-to-Programming-using-Python

Python
5
star
78

client

React boiler plate
JavaScript
5
star
79

text-analyzer

It counts the most frequent words in a chunk of text
JavaScript
5
star
80

JavaScript-lesson-Dec-2020

JavaScript
5
star
81

react-redux-thunk-boilerplate

JavaScript
5
star
82

Bootstrap

Bootstrap Portfolio
HTML
5
star
83

HTML5

Github first time
HTML
4
star
84

mongo-basics

JavaScript
4
star
85

Python-Crash-Course

Python
4
star
86

JavaScript

HTML
4
star
87

python-in-amharic

Python
4
star
88

REST-API-Express

JavaScript
4
star
89

sentiment-analysis-with-textblob

Jupyter Notebook
4
star
90

Python

Python
4
star
91

web-form-regex

JavaScript
4
star
92

python-autumn-2024-arbis

Python
4
star
93

react-basic

JavaScript
3
star
94

NodeSchool-JS-Exercises

JavaScript
3
star
95

basic-node

JavaScript
3
star
96

CI-CD

Python
3
star
97

mustangs

HTML
3
star
98

node.js-simple-example

JavaScript
3
star
99

Introduction-to-Data-Science

Python
3
star
100

Node

HTML
3
star