
|
|
|||
JavaScript FunctionsWhen writing code, sometimes you will want to perform a certain task repeatedly. Instead of writing out the code again and again, you can create a function. Declaring a JavaScript function
In this example, we create the function
The only space we need here is between The parameter list follows, as we discussed for document.write
earlier. The parameter list is enclosed in parenthesis and can be left
empty but must remain. We then show the start of the function with a open curly brace; in this case, Function names are roughly the same as variable names: start with a letter or underscore, then a mix of letters, numbers and underscores. Calling a JavaScript functionWhen we use a JavaScript function, we say we called the function. Here's an example.
In this example, we define the function writeToDocument. It takes one parameter: We then call our new function a few times. We can call it as many times as we like. We can also do as much as we want inside the function, and we can also call other functions. Default parameter valuesSometimes you will want to set a default value for the function
parameter. The parameter list - the section in parenthesis after the
function name - is just like the
In this way, if a parameter is not specified when the function is called it is assigned the default value. Returning a value from a JavaScript functionNow, a function can do something, but maybe you want it to help you with a variable you have at the moment. For example, what if we have a number and we want to add 10 to it? We could write a JavaScript function that would add ten to the number.
This example will output:
The Here, we pass JavaScript has many inbuilt functions. A common one you will encounter is alert(), which creates a popup box with text you specify (through a parameter) and an 'OK' button. Consider this example:
The Now that we understand functions, let's look at some JavaScript condition structures.
|
||||
| About the NetVisits, Inc Network | Write For Us | Advertise Copyright ©2007 NetVisits, Inc Network. All Rights Reserved. Privacy Policy. |
Visit other NetVisits, Inc. sites: |