Higher Order Functions in JavaScript🚀

Higher Order Functions in JavaScript🚀

Here we'll learn about all the different HOF in JavaScript.

Higher Order Functions🤔

A function that receives another function as an argument or that returns a new function or both is called Higher-order-functions. Basically, a function which takes another function as an argument or returns a function is known as a higher order function.

Let's talk about some of the important Higher Order functions here:

setTimeout()

setTimeout() function accepts a callback function as an argument with a specified time and executes the callback function after that specified time. It basically delays a function call up for time being specified in the parameter. The commonly used syntax is:

setTimeout(function, milliseconds);

Its parameters are:

  • function - a function containing a block of code
  • milliseconds - the time after which the function is to be executed

    Example 1:

    // program to demonstrate setTimeout()
    setTimeout(()=> (
      console.log('The statement will pe printed after 3 seconds')
    ),3000);
    console.log("The statement will be executed immediately after the program runs");
    

    Output:

    image.png

Example 2:


// program to print a number every second using setTimeout()
// Remember that the order doesn't matter here
// the function will be executed after only the milliseconds given are passed

setTimeout(()=> (
    console.log('1')
),2000);
setTimeout(()=> (
    console.log('2')
),3000);
setTimeout(()=> (
    console.log('3')
),1000);
setTimeout(()=> (
    console.log('4')
),4000);

console.log("The statement will be printed immediately");
console.log('Now statements will be printed st each sec');

Output:

The statement will be printed immediately
Now statements will be printed st each sec
3
1
2
4

JavaScript setInterval()

The setInterval() method repeats a block of code at every given timing event.

The commonly used syntax of JavaScript setInterval is:

setInterval(function, milliseconds);

Its parameters are:

  • function - a function containing a block of code
  • milliseconds - the time interval between the execution of the function

    Example 1

    // program to print a number every second
    // it will run infintely
    setInterval(()=>console.log("Hello There"),1000);
    

    Output:

image.png

The setInterval() method returns an interval ID

image.png The following ID can be used to stop the execution of setInterval() method. We use clearInterval() method to stop the execution of interval, it accepts the unique Id of the interval.

// program to print a number every second for five seconds
const uniqueId = setInterval(() => {
    console.log("Hello There");
    setTimeout(()=> (
        clearInterval(uniqueId)
    ),5000);
},1000);

In the above program, the setInterval() method prints "Hello There after every 1 sec and setTimeout() executes after 5 sec. The setTimeout() executes the block of code with clearInterval(uniqueId) which stops the execution of setInterval() after 5 sec.

Javascript Array filter()

The filter() method returns a new array with all elements that pass the test defined by the given function.

filter() Syntax

The syntax of the filter() method is:

arr.filter(callback(element), thisArg)

Here, arr is an array.

Example 1:

// program using filter to extract all strings from arr
const arr = [12, 13, "FSJS", true, "Developer"];
let newArr = arr.filter((item)=>{
    if(typeof item === "string") return true;
    else return false;
})
console.log(newArr);
// Output: [ 'FSJS', 'Developer' ]

Example 2:

//program to filter all even numbers and strings from array
const arr = [12, 13, 14., true, false, "React js", "Next Js"];
let newArr = arr.filter((item) => {
    if(typeof item ==="string") return true;
     else if(typeof item === "number" && item%2==0) return true; 
     else return false;
    })
 console.log(newArr);   

//  Output: [ 12, 14, 'React js', 'Next Js' ]

JavaScript Array map()

The map() method creates a new array with the results of calling a function for every array element.

map() Syntax

The syntax of the map() method is:

arr.map((item) => {
//block of code
})

Let's write a code snippet to print all elements of an array.

// using map method method to traverse through the array
const arr = [12, 13, 14., true, false, "React js", "Next Js"];
arr.map((item)=>{
    console.log(item);
})

// Output: 12 13 14 true false React js Next Js

Example 1:

// program to get all strings from arr using map
const arr = [12, 13, 14., true, false, "React js", "Next Js"];
const newArray = [];
arr.map((item)=> {
    if(typeof item === 'string')
    newArray.push(item);
})
console.log(newArray);
// Output: [ 'React js', 'Next Js' ]

Array reduce()

The reduce() method executes a reducer function on each element of the array and returns a single output value. The arr.reduce() method is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.

Syntax:

// syntax:
array.reduce(callback_func, startIndex(optional))

reduce() Parameters:

array: The array on which the reduce function is to be performed.

callback_func: The function to execute on each array element (except the first element if no initialValue is provided). It takes in accumulator - It accumulates the callback's return values. Start with the first value of the array. currentValue - The current element being passed from the array.

startIndex: The starting index from where the reduce operation should begin on the array. The value is optional and starts with the first element of the array if not provided.

Examples:

The accumulator and currentValue is printed on console to analyze:

const numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue) => {
    console.log(`${accumulator} and ${currentValue}` )
    return accumulator+currentValue
});
console.log(sum);

Output:

image.png

Javascript Array every()

The JavaScript Array every() method checks if all the array elements pass the given test function.

Syntax:

The syntax of the every() method is:

arr.every(callback(currentValue), thisArg)

Here, arr is an array.

Return value from every()

  • Returns true if all array elements pass the given test function (callback returns a truthy value).
  • Otherwise, it returns false.

Let's understand with an example:

// program to check every element of array is even or not using every.
const arr = [2, 4, 6, 8, 10, 12];
const arr1 = [2, 4, 5, 8, 10];
 const check = arr.every((item) => {
    return item%2==0;
 })
 const check1 = arr1.every((item)=>{
    return item%2==0;
 })
 console.log(check)
 console.log(check1);
// Output: true 
// false

Hope, it was helpful. If it helped don't forget to smash the like button.