Because functions are such an important concept, here’s a series of steps for you to practice creating and using a function on a real web page:
Working with Function
Functions are even more useful when they receive information.JavaScript functions can also accept information, called parameters, which the function uses to carry out its actions.
To start, when you create the function, place the name of a new variable inside the parentheses - this is the parameter. The basic structure looks like this:
function functionName(parameter) {
// the JavaScript you want to run
}
The parameter is just a variable, so you supply any valid variable name.
You create a simple function that lets you replace the web browser’s document.write() function with a shorter name:
function print(message) {
document.write(message);
}
The name of this function is print and it has one parameter, named message. When this function is called, it receives some information and then it uses the document.write() function to write the message to the page.
You can call the above function like this:
print('Hello world.');
When working with functions, you usually create the function before you use it. The print() function here is created in the first three lines of code, but the code inside the function doesn’t actually run until the last line.
function print(message) {
document.write(message);
}
print( ’Hello world!’ );
A function isn’t limited to a single parameter, either. You can pass any number of arguments to a function. You just need to specify each parameter in the function, like this:
function functionName(parameter1, parameter2, parameter3) {
// the JavaScript you want to run
}
And then call the function with the same number of arguments in the same order:
functionName(argument1, argument2, argument3);
Here’s what the new function would look like:
function print(message,tag) {
document.write('<' + tag + '>' + message +'</' + tag + '>');
}
The function call would look like this:
print('Hello world.', 'p');
In this example, you’re passing two arguments -‘Hello world.’ and ‘p’ - to the function. Those values are stored in the function’s two variables—message and tag. The result is a new paragraph - <p>Hello world.</p> - printed to the page.
0 comments:
Post a Comment