A function is a block of code wrapped in curly braces, preceded by the keyword function:
Function parameters
The function can have as many parameters as you like. There is no need to declare the variable type, just give the variable name:
Function return value
When you use the return statement in a function, the function stops execution and returns to the place where it was called.
There is no need to declare a type for the return value of a function, it can be returned directly.
The above function will return a return value of 5.
Note: The entire JavaScript will not stop execution, just the function.
JavaScript will continue executing code from where the function was called.
Function calls will be replaced by return values:
When you just want to exit the function, you can also use the return statement.
Return value is optional:
When a is greater than b, the execution will no longer proceed, but will return directly.
Local variables
Let’s talk about local variables and global variables again here.
A variable declared inside a 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 the function that declares the variable can recognize the variable.
As soon as the function completes, the local variable will be deleted.
Global variables
Variables declared outside the function are global variables and can be accessed by all scripts and functions on the web page.
NOTE: Assigning values to undeclared JavaScript variables:
If you assign a value to a variable that has not been declared yet, the variable will automatically be declared as a global variable.
This sentence:
carname="Volvo";
A global variable carname will be declared, even if it is executed within a function.
Function instance