Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4. Function() > Passing Functions to Functions and Returning Functions from Fun...

Passing Functions to Functions and Returning Functions from Functions

As previously mentioned, functions are first-class citizens in JavaScript. And since a function is a value, and a function can be passed any sort of value, a function can be passed to a function. Functions that take and/or return other functions are sometimes called “higher-order functions.”

Below, we are passing an anonymous function to the foo function, which we then immediately return from the foo function. It is this anonymous function that the variable bar points to, since foo accepts and then returns the anonymous function.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

// functions can be sent to, and sent back from, functions
var foo = function(f) {
   return f;
}

var bar = foo(function() {console.log('Hi');});

bar(); // logs 'Hi'

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint