Higher Order Function: Callback
Higher Order Function: Callback
Callback
A callback is a function which can be passed as parameter to other function. See the example
below.
return n ** 2
function cube(callback, n) {
return callback(n) * n
console.log(cube(callback, 3))
Returning function
Higher order functions return function as a value
return 2 * n + 3 * m + t
return doWhatEver
}
return doSomething
console.log(higherOrder(2)(3)(10))
Let us see were we use call back functions. For instance the forEach method uses call back.
let sum = 0
sum += element
arr.forEach(callback)
return sum
console.log(sumArray(numbers))
15
let sum = 0
arr.forEach(function(element) {
sum += element
})
return sum
console.log(sumArray(numbers))
15
Setting time
In JavaScript we can execute some activities in a certain interval of time or we can schedule(wait)
for some time to execute some activities.
setInterval
setTimeout
In JavaScript, we use setInterval higher order function to do some activity continuously with in
some interval of time. The setInterval global method take a callback function and a duration as a
parameter. The duration is in milliseconds and the callback will be always called in that interval of
time.
// syntax
function callback() {
setInterval(callback, duration)
function sayHello() {
console.log('Hello')
In JavaScript, we use setTimeout higher order function to execute some action at some time in the
future. The setTimeout global method take a callback function and a duration as a parameter. The
duration is in milliseconds and the callback wait for that amount of time.
// syntax
function callback() {
function sayHello() {
console.log('Hello')
Functional Programming
Instead of writing regular loop, latest version of JavaScript introduced lots of built in methods
which can help us to solve complicated problems. All builtin methods take callback function. In this
section, we will see forEach, map, filter, reduce, find, every, some, and sort.
forEach
forEach: Iterate an array elements. We use forEach only with arrays. It takes a callback function with
elements, index parameter and array itself. The index and the array optional.
})
})
// The above code can be written using arrow function and explicit return
console.log(sum)
let sum = 0;
console.log(sum)
15
FINLAND
DENMARK
SWEDEN
NORWAY
ICELAND
map
map: Iterate an array elements and modify the array elements. It takes a callback function with
elements, index , array parameter and return a new array.
return element
})
*/
//Example
console.log(numbersSquare)
console.log(namesToUpperCase)
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya',
console.log(countriesToUpperCase)
/*
// Arrow function
return country.toUpperCase();
})
*/
country.toUpperCase().slice(0, 3)
["ALB", "BOL", "CAN", "DEN", "ETH", "FIN", "GER", "HUN", "IRE", "JAP", "KEN"]
filter
Filter: Filter out items which full fill filtering conditions and return a new array.
country.includes('land')
console.log(countriesContainingLand)
['Finland', 'Ireland']
console.log(countriesEndsByia)
['Albania', 'Bolivia','Ethiopia']
console.log(countriesHaveFiveLetters)
['Japan', 'Kenya']
const scores = [
console.log(scoresGreaterEighty)
[{name: 'Asabeneh', score: 95}, { name: 'Lidiya', score: 98 },{name: 'Martha', score: 85},{n
reduce
reduce: Reduce takes a callback function. The call back function takes accumulator, current, and
optional initial value as a parameter and returns a single value. It is a good practice to define an
initial value for the accumulator value. If we do not specify this parameter, by default accumulator
will get array first value . If our array is an empty array, then Javascript will throw an error.
return
}, initialValue)
console.log(sum)
15
every
every: Check if all the elements are similar in one aspect. It returns boolean
const areAllStr = names.every((name) => typeof name === 'string') // Are all strings?
console.log(areAllStr)
true
console.log(areAllTrue) // true
true
find
find: Return the first element which satisfies the condition
console.log(age)
18
console.log(result)
Asabeneh
const scores = [
console.log(score)
findIndex
findIndex: Return the position of the first element which satisfies the condition
console.log(result) // 0
console.log(age) // 5
some
some: Check if some of the elements are similar in one aspect. It returns boolean
console.log(areSomeTrue) //true
const areAllStr = names.some((name) => typeof name === 'number') // Are all strings ?
console.log(areAllStr) // false
sort
sort: The sort methods arranges the array elements either ascending or descending order. By
default, the sort() method sorts values as strings.This works well for string array items but not for
numbers. If number values are sorted as strings and it give us wrong result. Sort method modify
the original array. It is recommended to copy the original data before you start using sort method.
As you can see in the example below, 100 came first after sorted in ascending order. Sort converts
items to string , since '100' and other numbers compared, 1 which the beginning of the string '100'
became the smallest. To avoid this, we use a compare call back function inside the sort method,
which return a negative, zero or positive.
// Using sort method to sort number items provide a wrong result. see below
numbers.sort(function (a, b) {
return a - b
})
numbers.sort(function (a, b) {
return b - a
})
Whenever we sort objects in an array, we use the object key to compare. Let us see the example
below.
objArr.sort(function (a, b) {
return 0
})
// or
objArr.sort(function (a, b) {
return 0
})
const users = [
users.sort((a, b) => {
return 0
})
🌕 You are doing great.Never give up because great things take time. You have just completed
day 9 challenges and you are 9 steps a head in to your way to greatness. Now do some exercises
for your brain and for your muscle.
💻 Exercises
Exercises: Level 1
const products = [
Exercises: Level 2
1. Find the total price of products by chaining two or more array iterators(eg.
arr.map(callback).filter(callback).reduce(callback))
2. Find the sum of price of products using only reduce reduce(callback))
3. Declare a function called categorizeCountries which returns an array of countries which have
some common pattern(you find the countries array in this repository as countries.js(eg 'land',
'ia', 'island','stan')).
4. Create a function which return an array of objects, which is the letter and the number of times
the letter use to start with a name of a country.
5. Declare a getFirstTenCountries function and return an array of ten countries. Use different
functional programming to work on the countries.js array
6. Declare a getLastTenCountries function which which returns the last ten countries in the
countries array.
7. Find out which letter is used many times as initial for a country name from the countries array
(eg. Finland, Fiji, France etc)
Exercises: Level 3
1. Use the countries information, in the data folder. Sort countries by name, by capital, by
population
console.log(mostSpokenLanguages(countries, 10))
{country: 'English',count:91},
{country: 'French',count:45},
{country: 'Arabic',count:25},
{country: 'Spanish',count:24},
{country:'Russian',count:9},
{country:'Portuguese', count:9},
{country:'Dutch',count:8},
{country:'German',count:7},
{country:'Chinese',count:5},
{country:'Swahili',count:4}
console.log(mostSpokenLanguages(countries, 3))
]```
3. *** Use countries_data.js file create a function which create the ten most populated countries
console.log(mostPopulatedCountries(countries, 10))
console.log(mostPopulatedCountries(countries, 3))
```
4. *** Try to develop a program which calculate measure of central tendency of a sample(mean,
median, mode) and measure of variability(range, variance, standard deviation). In addition to
those measures find the min, max, count, percentile, and frequency distribution of the sample.
You can create an object called statistics and create all the functions which do statistical
calculations as method for the statistics object. Check the output below.
const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37
console.log('Count:', statistics.count()) // 25
console.log('Median: ',statistics.median()) // 29
console.log(statistics.describe())
Count: 25
Sum: 744
Min: 24
Max: 38
Range: 14
Mean: 30
Median: 29
Mode: (26, 5)
Variance: 17.5
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0,