Higher order functions are functions which take other function as a parameter or return a function as a value. The function passed as a parameter is called callback.
// 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))
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 :
setInterval(sayHello, 1000) // it prints hello in every second, 1000ms is 1s
setInterval higher order function to do some activity continuously with in some interval of time.
setTimeout
execute some action at some time in the future.
setTimeout(sayHello, 2000) // it prints hello after it waits for 2 seconds.
Functional Programming
forEach: Iterate an array elements
arr.forEach(function (element, index, arr) { console.log(index, element, arr) })
map: Iterate an array elements and modify the array elements.
/*Arrow function and explicit return const modifiedArray = arr.map(function (element, index, arr) { return element }) */ //Example const numbers = [1, 2, 3, 4, 5] const numbersSquare = numbers.map((num) => num * num) console.log(numbersSquare)
Filter: Filter out items which full fill filtering conditions and return a new array.
//Filter countries containing land const countriesContainingLand = countries.filter((country) => country.includes('land') ) console.log(countriesContainingLand)
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, thenJavascript
will throw an error.arr.reduce((acc, cur) => { // some operations goes here before returning a value return }, initialValue)
const numbers = [1, 2, 3, 4, 5] const sum = numbers.reduce((acc, cur) => acc + cur, 0) console.log(sum)