Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    1Topic
    |
    1 Quiz
Lesson 8, Topic 3
In Progress

JavaScript: Functions as Parameters

Yasin Cakal 25 Nov 2021
Lesson Progress
0% Complete

Functions in JavaScript behave like any other type of data, it should come as no surprise that we can pass functions (into other functions) as parameters. A higher-order function takes functions as input, returns a function, or does both! Because they are called during the execution of the higher-order function, we refer to the functions that are passed in as parameters as callback functions.


We don’t invoke a function when we pass it as an argument to another function. The return value of that function call would be evaluated when the function is invoked. When using callbacks, we type the function name without the parentheses ( ) (which will evaluate to the function’s result):

const timeFuncRuntime = funcParameter => {
   let time1 = Date.now();
   funcParameter();
   let time2 = Date.now();
   return time2 - time1;
}
const add = () => 1 + 1;
timeFuncRuntime(add);

We created timeFuncRuntime, a higher-order function. It takes a function as an argument, saves a starting time, calls the callback function, records the time after the function was called, and subtracts the starting time from the ending time to get the time the function took to run.

The higher-order function can be used with any callback function, it has the potential to be a very useful piece of code. We then used the add() function to call timeFuncRuntime() – note that we passed in add but did not call it.

 timeFuncRuntime(() => {
  for (let i = 10; i>0; i--){
    console.log(i);
  }
});

We used an anonymous function to call timeFuncRuntime() in this example, which counts backward from 10. Anonymous functions can also be used as arguments.

Responses

Leave a Reply

%d bloggers like this: