You first declare the function. You can then call the function.
Declare a Function
To declare a function, write the word
function followed by the name of the function, the function's parameters (in parentheses), and then the function's code block.
Parameters in Functions
The parentheses after the function name allow you to store parameters for the function. Parameters are variables that the function works with. When you call the function in your web page code, you can pass the function specific values for the parameters, and those values will replace the parameters in the function's code.
Here's an example function with 4 parameters:
The function has four parameters:
location. These parameters can be manipulated in the code block as variables.
Note that as you're declaring functions, you can include variables inside your function, as the previous example does with
var widgetTotal. If you do list variables here, they'll only be available inside the function. You won't be able to call the variable in other places. If you want to use the variable outside the function, you must declare it outside the function.
Calling a Function
To call a function, type the name of the function and include specific values for the parameters, like this:
These values are then passed into the function's parameters. Essentially you're saying
var quadrant = 2, size = 300, duration = 6000, location = 50;. The function then runs the code block using those specific values.
If you pass too many parameters to your function, the extra parameters are ignored. In the following example, the
"John Doe" and
65 are ignored:
The following example doesn't have enough parameters:
The missing parameters will be treated as undefined in the function. These undefined parameters may or may not break your function's code. It depends on how you've written the function.
Functions don't just accept incoming information. Functions can also return information. When you add
return in your function code, the function will send that information back. Here's an example:
In this example, the value for widgetTotal will be passed back to the place where you called the function.
I'd Rather Be Writing Newsletter
Get new posts delivered straight to your inbox.