05.01.2013 Views

hide - Understanding jQuery

hide - Understanding jQuery

hide - Understanding jQuery

SHOW MORE
SHOW LESS

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

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

It’s not important always necessary to understand that variables are actually objects. It is possible<br />

to write programs thinking of variables as variables. However, as you learn more and enable<br />

yourself to write more complex programs the knowledge of objects becomes important.<br />

Functions as Objects<br />

Even functions in JavaScript are objects. Below, we will consider the function add. add is the<br />

name of the function. You can also think of it as an object called add.<br />

Let’s consider this simple example:<br />

function add(a, b)<br />

{<br />

var result = a + b;<br />

return result;<br />

}<br />

This is a function definition. To define a function we start with the keyword function. This is<br />

followed by a custom name. The point of this function is to add two numbers. You are the one<br />

who determines the purpose, and therefore, the name of your new function.<br />

You will write the logic of the code of this function. In this example we are adding two numbers<br />

and return the result.<br />

Notice a and b in parenthesis just after the function name. These two values will be “passed” to<br />

the function at the time of program execution. Below you will see that I am passing the arbitrary<br />

numbers 10 and 5 to this function.<br />

Of course we are not limited to just two parameters. We could have just one paramter a or<br />

many more if required. Multiple parameters are separated by comma, so we have add(a, b).<br />

Within the function definition itself a and b are called parameters. We use these parameters to<br />

determine what this function will do with them. But when we execute the function, the actual<br />

values passed as parameters are called arguments. It’s easy to memorize because a parameter is<br />

always represented by one letter or word but an argument can be a statement like 1 + 2. In the<br />

example below 10 and 5 are this function’s arguments. They are passed as parameters a and b.<br />

var result = add(10, 5);<br />

By the time this statement finishes executing the variable result will store the return value of<br />

15 because 10 + 5 is 15. Inside the function, the value is returned using the return keyword.<br />

Notice that return is a reserved keyword. We cannot have a variable called return. In other<br />

words the code var return = 12; will generate a syntax error.<br />

17

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

Saved successfully!

Ooh no, something went wrong!