06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Functions, Closures, and Modules<br />

As with any other object in <strong>JavaScript</strong>, functions have the following capabilities:<br />

• They can be created via literals<br />

• They can be assigned to variables, array entries, and properties of other<br />

objects<br />

• They can be passed as arguments to functions<br />

• They can be returned as values from functions<br />

• They can possess properties that can be dynamically created and assigned<br />

We will talk about each of these unique abilities of a <strong>JavaScript</strong> function in this<br />

chapter and the rest of the book.<br />

A function literal<br />

One of the most important concepts in <strong>JavaScript</strong> is that the functions are the<br />

primary unit of execution. Functions are the pieces where you will wrap all your<br />

code, hence they will give your programs a structure.<br />

<strong>JavaScript</strong> functions are declared using a function literal.<br />

Function literals are composed of the following four parts:<br />

• The function keyword.<br />

• An optional name that, if specified, must be a valid <strong>JavaScript</strong> identifier.<br />

• A list of parameter names enclosed in parentheses. If there are no parameters<br />

to the function, you need to provide empty parentheses.<br />

• The body of the function as a series of <strong>JavaScript</strong> statements enclosed in braces.<br />

A function declaration<br />

The following is a very trivial example to demonstrate all the components of a<br />

function declaration:<br />

function add(a,b){<br />

return a+b;<br />

}<br />

c = add(1,2);<br />

console.log(c); //prints 3<br />

[ 46 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!