Functions are event-driven, or reusable blocks of code that are executed when they are invoked.
Example
1<! DOCTYPE html>234<script>5 functionmyFunction ()6 {7Alert ("Hello world!");8 }9</script>Ten One A<body> -<button onclick= "myFunction ()" >try it</button> -</body> theJavaScript function syntaxA function is a block of code enclosed in curly braces, declared with the keyword funtion
function functionname () {Execute code}
Executes the code in the function body when the function is called.
Or it can be triggered by an event (such as a user clicking on a button) and can be called from anywhere by JavaScript.
Calling a function with parametersWhen a function is called, arguments can be passed to it, and parameters can be called in the body of the function, with the number of arguments being arbitrary and separated by commas.
When declaring a function, declare the argument as a variable:
function myFunction (VAR1,VAR2) {code}
Variables and parameters must appear in a consistent order. The first variable is the given value of the first parameter passed, and so on.
function with return valueSometimes we want the function to return a value to the place where it was called, by using the return statement to implement, the return statement will return a value, and let the function end.
function myFunction () { var x=5; return x;}
The above function returns the value 5.
Example:
function MyFunction (b) { return A *b;} document.getElementById ("Demo"). innerhtml= MyFunction (4,3);
The InnerHTML of the "demo" element will be: 12
You can also use the return statement only if you want to exit the function. The return value is optional:
function MyFunction (b) { if (a>b) { return; } x=a+B}
If a is greater than B, the above code exits the function and does not calculate the sum of a and B.
Local JavaScript variablesA variable declared in a function whose scope is local and can only be used in the function.
Different functions can declare local variables of the same variable name, because only the function that declares the variable can recognize the variable.
At the end of the function, the local variable is deleted.
Global JavaScript variablesVariables declared outside the function are global variables, and all scripts and functions on the Web page can access it.
The lifetime of a JavaScript variableThe life cycle of JavaScript variables begins when they are declared, local variables are deleted after the function finishes executing, and global variables are deleted when the page is closed.
Assigning values to undeclared JavaScript variablesIf you assign a value to a variable that has not been declared, the variable is automatically declared as a global variable, even if it is assigned in a function.
Example:
Carname= "Volvo";
A global variable carname is declared.
(2) JavaScript functions