JS Functions or Java script Functions
A function is a code block that can repeat to run many times. To define a function, use “function function name () {}”.
1 |
function function-name () {......} |
To call a function, use “function-name ();”
function-name ();
How to create function in JavaScript Ex,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<html> <head> <script type="text/JavaScript"> function test() { // declare a function alert("Visit phpgurukul.com!"); // output } </script> </head> <body onload="test()"> <!-- call the function --> </body> </htm |
Output
Visit phpgurukul.com!
Explanation:
"function test() {}"
is a declaration of test() function. onload="test()"
calls function test()
after the web has loaded.
"test()"
is a command to call a function named test(){}
. When running the function test (), it will output “Call a function!”.
Function with Arguments
A function can have one or more arguments inside the bracket. Arguments are used to pass data to function.
1 |
function function-name (var arg) {……} |
To call a function, use “function-name (argument);”
1 |
function-name (argument); |
Ex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<html> <head> <title> JavaScript Test </title> <script type="text/JavaScript"> function test(msg) { // declare a function arguments alert(msg); // output the value of msg } </script> </head> <body onload="test('Call a function with arguments')"> <!--call the function and pass arguments--> </body> </html> |
Output:
Call a function with arguments
Explanation:
onload=”test(“…”)” calls function test(msg) after the
web has loaded.
When test("Call a function with arguments.")
calling the function test(msg){…},
it will pass the “Calla function with arguments” to var msg. After var msg has received the data, it will pass the data inside the function. alert (msg)
will use the data, and then outputs “Call a function with arguments”.