17.11.2015 Views

JavaScript_Succinctly

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

the bar variable. All this is to showcase the fact that functions can be passed around<br />

just like any other value.<br />

Invoking function statements before they are defined (aka function<br />

hoisting)<br />

A function statement can be invoked during execution before its actual definition. This is<br />

a bit odd, but you should be aware of it so you can leverage it, or at least know what’s<br />

going on when you encounter it. In the following sample, I invoke the sayYo() and<br />

sum() function statements before they are defined.<br />

Sample: sample96.html<br />

<br />

// Example 1<br />

var speak = function () {<br />

sayYo(); // sayYo() has not been defined yet, but it can still be<br />

invoked, logs 'yo'.<br />

function sayYo() { console.log('Yo'); }<br />

} (); // Invoke<br />

// Example 2<br />

console.log(sum(2, 2)); // Invoke sum(), which is not defined yet, but<br />

can still be invoked.<br />

function sum(x, y) { return x + y; }<br />

<br />

This happens because before the code runs, function statements are interpreted and<br />

added to the execution stack/context. Make sure you are aware of this as you use<br />

function statements.<br />

Notes<br />

Functions defined as function expressions are not hoisted. Only function statements are<br />

hoisted.<br />

A function can call itself (aka recursion)<br />

It’s perfectly legitimate for a function to call itself. In fact, this is often used in well-known<br />

coding patterns. In the code that follows, we kick off the countDownFrom function, which<br />

then calls itself via the function name countDownFrom. Essentially, this creates a loop<br />

that counts down from 5 to 0.<br />

102

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!