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() > Self-Invoking Anonymous Function Statements

Self-Invoking Anonymous Function Statements

It’s possible to create an anonymous function statement that is self-invoked. This is called a self-invoking anonymous function. Below, we create several anonymous functions that are immediately invoked.

Live Code

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

// most commonly used/seen in the wild
(function(msg) {
   console.log(msg);
})('Hi');

// slightly different but achieving the same thing:
(function(msg) {
   console.log(msg)
}('Hi'));

// the shortest possible solution
!function sayHi(msg) {console.log(msg);}('Hi');

// FYI, this does NOT work!
// function sayHi() {console.log('hi');}();

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

Note

According to the ECMAScript standard, the parentheses around the function (or anything that transforms the function into an expression) are required if the function is to be invoked immediately.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

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

  

Start a Free 10-Day Trial


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