DEV Community

Rahil Rehan
Rahil Rehan

Posted on

Javascript Notes, Part-02 - Callbacks and Higher-order functions

Remember one word when you write code, "DRY" (Don't Repeat Yourself).

Higher-order functions and callbacks.

Most of the code can be optimized, shortened, and modularized while writing functions. If you can modularly write code that doesn't repeat the same functionality then you are following the DRY principle.

Some DRY principles

Generalization: First try to generalize your functions. If two functions do the same things then probably they can be combined to one.
Example:

function nineSquared() {
 return 9*9;
}

function tenSquared() {
 return 10*10;
}

//above code is not DRY

 function numSquared(num){
  return num*num
}

//generalized function

Enter fullscreen mode Exit fullscreen mode

Functions are first-class objects

  • They can be assigned to variables.
  • They can be passed as arguments.
  • Can be returned from other functions.

Higher-order functions: A function that takes in a function as an argument or returns out a function.
Callback functions: Functions that are passed in as parameters to higher-order functions are called as callback functions.

We can use a callback function to DRY our code. Look at the below example where multiplyBy2 function acts as a callback function. Note that you can pass in
different functions as a callback function.

function copyArrayAndAdd3(array) {
 const output = [];
 for (let i = 0; i < array.length; i++) {
 output.push(array[i] + 3);
 }
 return output;
 }
const myArray = [1,2,3];
const result = copyArrayAndAdd3(myArray);

//we are breaking the DRY principle in above

function copyArrayAndManipulate(array, instructions) {
 const output = [];
 for (let i = 0; i < array.length; i++) {
 output.push(instructions(array[i]));
 }
 return output;
}
function multiplyBy2(input) { return input * 2; }
const result = copyArrayAndManipulate([1, 2, 3], multiplyBy2);

//Here multipleBy2 is passed as callback function to higher-order function copyArrayAndManipulate.
//This callback function can be later invoked inside the parent function.
// multipleBy2 can be replaced with other functions, hence our code is DRY!
Enter fullscreen mode Exit fullscreen mode

Some Notes:

  • Async JS: callbacks are the core aspect of async JS

  • Parameters are passed in as a link back to where it was saved in global, We are not copying but sending the reference of the variable into a function.

  • Blocks like for loop get their own protected namespace but not an entire execution context.

  • Methods, They can be passed as inputs, as arguments into other functions, they reference back to where they were born, more on this later.

Top comments (0)