DEV Community

Ranjith srt
Ranjith srt

Posted on

js | Higher-order Functions |

Higher-order Functions:

Functions that take other functions as arguments or return them as results.


function startEngine() {

return 'is started!';

}

Enter fullscreen mode Exit fullscreen mode

// Higher-order function
function drive(driverName, engine) {

const message = engine(); // Callback function

console. Iog(' ${message} by ${driverName}' )

}

drive( ' Alex ' , startEngine);

Enter fullscreen mode Exit fullscreen mode

output:


Engine is started! by Alex

Enter fullscreen mode Exit fullscreen mode

Pure Functions: Functions that, given the same input,will always return the same output and have no side effects.

Higher-order Functions:


// Pure function
functionadd(a, b) {

return a + b;

console.log(add(2,3)); //5
console.log(add(2,3));  //5
console.log(add(2,3)); //5

Enter fullscreen mode Exit fullscreen mode

Impure function


let counter =0;

function increment(value) {

   counter += value;
   return counter;

}


console.log(increment(2)); 2
console.log(increment(2)); 4
console.log(increment(2)); 6

Enter fullscreen mode Exit fullscreen mode

Top comments (0)