This article briefly introduces the concepts of functions in javascript, as well as the function parameters, return values, local variables, global variables, and examples. It is a very good article and is recommended for you to learn. A function is a block of code enclosed in curly braces. The keyword function is used before:
The Code is as follows:
Function functionName ()
{
Here is the code to be executed
}
Function Parameters
Function parameters can be any number, without declaring the variable type. Only the variable name is given:
The Code is as follows:
Function myFunction (name, job)
{
Here is the code to be executed
}
Function return value
When a return statement is used in a function, the function stops execution and returns the place where it is called.
The Return Value of the function does not need to be declared. You can directly return the value.
The Code is as follows:
Function myFunction ()
{
Var x = 5;
Return x;
}
The preceding function returns the value 5.
Note: The entire JavaScript will not stop execution, but it is just a function.
JavaScript will continue to execute the code from where the function is called.
Function calls will be replaced by return values:
The Code is as follows:
Var myVar = myFunction ();
You can use the return statement only when you want to exit the function.
The return value is optional:
The Code is as follows:
Function myFunction (a, B)
{
If (a> B)
{
Return;
}
X = a + B;
}
If a is greater than B, it will not be executed but will be returned directly.
Local variable
Repeat the local variables and global variables here.
The variable declared inside the JavaScript function (using var) is a local variable, so it can only be accessed inside the function. (The scope of this variable is local ).
You can use local variables with the same name in different functions, because only functions that have declared the variable can recognize the variable.
After the function is run, the local variable is deleted.
Global Variables
The variable declared outside the function is a global variable, and all scripts and functions on the web page can access it.
Note: assign values to undeclared JavaScript variables:
If you assign a value to a variable that has not been declared, the variable is automatically declared as a global variable.
This statement:
Carname = "Volvo ";
A global variable carname will be declared even if it is executed in the function.
Function instances
The Code is as follows: