06.07.2017 Views

Mastering JavaScript

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

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

Functions, Closures, and Modules<br />

return 'trueMoo';<br />

};<br />

}<br />

else {<br />

sayMoo = function() {<br />

return 'falseMoo';<br />

};<br />

}<br />

foo();<br />

If you are curious to know why you should not use function declarations in<br />

conditional blocks, read on; otherwise, you can skip the following paragraph.<br />

Function declarations are allowed to appear only in the program or function body.<br />

They cannot appear in a block ({ ... }). Blocks can only contain statements and<br />

not function declarations. Due to this, almost all implementations of <strong>JavaScript</strong> have<br />

behavior different from this. It is always advisable to never use function declarations<br />

in a conditional block.<br />

Function expressions, on the other hand, are very popular. A very common pattern<br />

among <strong>JavaScript</strong> programmers is to fork function definitions based on some kind<br />

of a condition. As such forks usually happen in the same scope, it is almost always<br />

necessary to use function expressions.<br />

The arguments parameter<br />

The arguments parameter is a collection of all the arguments passed to the function.<br />

The collection has a property named length that contains the count of arguments,<br />

and the individual argument values can be obtained using an array indexing<br />

notation. Okay, we lied a bit. The arguments parameter is not a <strong>JavaScript</strong> array, and<br />

if you try to use array methods on arguments, you'll fail miserably. You can think of<br />

arguments as an array-like structure. This makes it possible to write functions that<br />

take an unspecified number of parameters. The following snippet shows you how<br />

you can pass a variable number of arguments to the function and iterate through<br />

them using an arguments array:<br />

var sum = function () {<br />

var i, total = 0;<br />

for (i = 0; i < arguments.length; i += 1) {<br />

total += arguments[i];<br />

}<br />

return total;<br />

};<br />

console.log(sum(1,2,3,4,5,6,7,8,9)); // prints 45<br />

console.log(sum(1,2,3,4,5)); // prints 15<br />

[ 60 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!