Table of contents
Introduction
Hey folks, I hope that you must have read my Day 8 Article on #30DaysOfJs. In case, if you haven't then make sure you give it a read by clicking here.
Higher Order Function
Higher order functions are functions that take other functions as a parameter or return a function as a value. The function which is passed as a parameter is called a callback.
Callback: A callback is a function that can be passed as a parameter to another function.
For Example:
// A callback function, the name of the function could be any name
const callback = (n) => {
return n ** 2
}
// Function that takes other function as a callback
function cube(callback, n) {
return callback(n) * n
}
console.log(cube(callback, 3));
Returning Function: Higher order functions return function as a value.
For Example 1:
// Higher order function returning an other function
const higherOrder = n => {
const doSomething = m => {
const doWhatEver = t => {
return 2 * n + 3 * m + t
}
return doWhatEver
}
return doSomething
}
console.log(higherOrder(2)(3)(10));
For Example 2: The below example is taken using forEach method.
const numbers = [1, 2, 3, 4, 5]
const sumArray = arr => {
let sum = 0
const callback = function(element) {
sum += element
}
arr.forEach(callback)
return sum
}
console.log(sumArray(numbers)); // Output -> 15
Setting Time: In JavaScript, we can execute some activities in a certain interval of time.
setInterval
setTimeout
- Using setInterval: In JavaScript, we use setInterval higher order function to do some activity continuously within some interval of time. The setInterval global method takes 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() {
// Code
}
setInterval(callback, duration)
For Example:
function sayHello() {
console.log('Hello')
}
setInterval(sayHello, 1000) // Prints hello in every second, 1000ms is 1s
- Using setTimeout: In JavaScript, we use the setTimeout higher order function to execute some action at some time in the future. The setTimeout global method takes a callback function and a duration as a parameter. The duration is in milliseconds and the callback waits for that amount of time.
function callback() {
// Code
}
setTimeout(callback, duration) // Duration in milliseconds
For Example:
function sayHello() {
console.log('Hello')
}
setTimeout(sayHello, 2000) // Prints hello after it waits for 2 seconds.
Functional Programming
Instead of writing regular loops, the latest version of JavaScript introduced lots of built-in methods that can help us to solve complicated problems. All built-in methods take callback functions some of them are: forEach, map, filter, every, and find.
- forEach: Used for iterating in arrays. It takes a callback function with elements, index parameters, and the array itself.
Syntax:
arr.forEach(function (element, index, arr) {
console.log(index, element, arr)
})
// Above code can be written using arrow function
arr.forEach((element, index, arr) => {
console.log(index, element, arr)
})
// Above code can be written using arrow function and explicit return
arr.forEach((element, index, arr) => console.log(index, element, arr))
For Example:
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland']
countries.forEach((element) => console.log(element.toUpperCase()))
// Output -->
// FINLAND
// DENMARK
// SWEDEN
// NORWAY
// ICELAND
- map: Used for iterating in arrays and modifying the elements. It takes a callback function with elements, and index parameters, and returns a new array.
Syntax:
const modifiedArray = arr.map(function (element, index, arr) {
return element
})
For Example:
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const namesToUpperCase = names.map((name) => name.toUpperCase())
console.log(namesToUpperCase);
// Output -->
// ['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK']
- filter: Used for filtering out items and returning a new array.
For Example 1:
//Filter countries containing land
const countriesContainingLand = countries.filter((country) =>
country.includes('land')
)
console.log(countriesContainingLand);
// Output -->
// ['Finland', 'Ireland']
For Example 2:
const scores = [
{ name: 'Asabeneh', score: 95 },
{ name: 'Lidiya', score: 98 },
{ name: 'Mathias', score: 80 },
{ name: 'Elias', score: 50 },
{ name: 'Martha', score: 85 },
{ name: 'John', score: 100 },
]
const scoresGreaterEighty = scores.filter((score) => score.score > 80)
console.log(scoresGreaterEighty);
// Output -->
// [{name: 'Asabeneh', score: 95}, { name: 'Lidiya', score: 98 },{name: 'Martha', score: 85},{name: 'John', score: 100}]
- every: Used for checking if all the elements are similar in one aspect. It returns the output in boolean.
For Example 1:
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const areAllStr = names.every((name) => typeof name === 'string')
console.log(areAllStr);
// Output -->
// true
For Example 2:
const bools = [true, true, true, true]
const areAllTrue = bools.every((b) => b === true)
console.log(areAllTrue);
// Output -->
// true
- find: Used for returning the first element which satisfies the condition.
For Example 1:
const ages = [24, 22, 25, 32, 35, 18]
const age = ages.find((age) => age < 20)
console.log(age);
// Output -->
// 18
For Example 2:
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const result = names.find((name) => name.length > 7)
console.log(result);
// Output -->
// Asabeneh
I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!
Who knows you might become a great programmer 🤔!