`
You've been using built-in functions. Now you will learn how to define your own functions.
The idea behind functions is that you want to write some block of code (function) once and reuse it. The basic structure for defining a function looks like this:
function functionName(){ // javascript code you want to run // ... // ... }- The keyword function lets the interpreter know you are creating a function.
Here the name of the function is printToday.
It has two lines of JavaScript code. Usually you put the function at the beginning of a script. Note that it will not run when it is created/defined. You need to call it.
function printToday(){ var today = new Date(); // create a Date object and put it into the variable today document.write(today.toDateString() + " "); // convert to string the date represented by variable today document.write(today.toTimeString()); // convert to string the time represented by variable today document.write("<br>"); }
<!DOCTYPE html> <html> <head> <title> The Title of this HTML Page </title> <script> function printToday(){ var today = new Date(); // create a Date object and put it into the variable today document.write(today.toDateString() + " "); // convert to string the date represented by variable today document.write(today.toTimeString()); // convert to string the time represented by variable today document.write("<br>"); } </script> </head> <body> This is the body. <br> <script> printToday(); // calling a function </script> </body> </html>
<!DOCTYPE html> <html> <head> <title> The Title of this HTML Page </title> <script> function printHello(){ document.write("hello <br>"); } </script> </head> <body> <script> printHello(); printHello(); printHello(); printHello(); </script> </body> </html>
function functionName(parameter1, parameter2, parameter3,...) { // javascript code }
functionName(parameter1, parameter2, parameter3, ...);
var answer = prompt("What is your name?");
var answer = "Reed";
function functionName(paramater1, parameter2) {
//java script code
return somevalue;
}
<!DOCTYPE html> <html> <head> <title> The Title of this HTML Page </title> <script> // name is a parameter and can be used just a variable var TAX= .08; // 8% sales tax function calculateTotal(quantity, price){ var total = quantity * price * (1 + TAX); return total; } </script> </head> <body> <script> var salesTotal = calculateTotal(3, 15); document.write("Total price: $" + salesTotal + "<br>"); </script> </body> </html>
<!DOCTYPE html> <html> <head> <title> The Title of this HTML Page </title> <script> /* A function that generates random color found on the Internet */ function get_random_color() { return "#" + (Math.round(Math.random() * 0XFFFFFF)).toString(16); } </script> </head> <body> <script> document.body.style.backgroundColor = get_random_color(); </script> </body> </html>