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() > Invoking Function Statements Before They Are Defined (Function ...

Invoking Function Statements Before They Are Defined (Function Hoisting)

A function statement can be invoked during execution before its actual definition. This is a bit odd, but you should be aware of it so you can leverage it, or at least know what’s going on when you encounter it. Below, I invoke the sayYo() and sum() function statements before they are defined.

Live Code

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

// Example 1

var speak = function() {
    sayYo(); /* sayYo() has not been defined yet but it can still be invoked, 
             logs 'yo' */
    function sayYo() {console.log('Yo');}
}(); // invoke

// Example 2

console.log(sum(2, 2)); /* invoke sum(), which is not defined yet, 
                        but can still be invoked */
function sum(x, y) {return x + y;}

</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 10-Day Trial


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