Java Reference
In-Depth Information
others simply perform an action but return no data. You'll also notice that some functions can be
passed data, whereas others cannot. For example, the isNaN() function needs to be passed some
data, which it checks to see if it is NaN . The data that a function requires to be passed are known as
its parameter(s) .
As you work your way through the topic, you'll be coming across many more useful built‐in
functions, but wouldn't it be great to be able to write your own functions? After you've worked out,
written, and debugged a block of code to perform a certain task, it would be nice to be able to call
it again and again when you need it. JavaScript enables us to do just that, and this is what you'll be
concentrating on in this section.
Creating Your oWn funCtions
Creating and using your own functions is
very simple. Figure 4-1 shows an example of a
function declaration.
You've probably already realized what this
function does and how the code works. Yes,
it's the infamous Fahrenheit‐to‐centigrade
conversion code again.
Each function you define in JavaScript must be
given a unique name for that particular page.
The name comes immediately after the function keyword. To make life easier for yourself, try using
meaningful names so that when you see them being used later in your code, you'll know exactly
what they do. For example, a function that takes as its parameters someone's birthday and today's
date and returns the person's age could be called getAge() . However, the names you can use are
limited, much as variable names are. For example, you can't use words reserved by JavaScript, so you
can't call your function if() or while() .
The parameters for the function are given in parentheses after the function's name. A parameter is
just an item of data that the function needs to be given in order to do its job. Usually, not passing the
required parameters will result in an error. A function can have zero or more parameters, though
even if it has no parameters, you must still put the open and close parentheses after its name. For
example, the top of your function definition must look like the following:
figure 4-1
function myNoParamFunction()
You then write the code, which the function will execute when called on to do so. All the function
code must be put in a block with a pair of curly braces.
Functions also enable you to return a value from a function to the code that called it. You use the
return statement to return a value. In the example function given earlier, you return the value of
the variable degCent , which you have just calculated. You don't have to return a value if you don't
want to, but it's important to note that every function returns a value even if you don't use the
return statement. Functions that do not explicitly return a value—that is, return a value with the
return statement—return undefined .
 
Search WWH ::




Custom Search