JavaScript function definitions

JavaScript function by function keyword definitions.

You can use function declarations or function expressions

Function block is wrapped in braces, the previously used Keywords function:

function functionName () 
{ 
         // execute code 
}

 

When the function is called, it will execute the code within the function.

You can directly call a function when an event occurs (such as when the user clicks a button), and can be JacaScript be called at any position.

JavaScript is case sensitive. Keyword function must be lowercase, and must be the same case with the function name to call the function.

 

 

Function calls with arguments

When calling a function, that can be passed values, these values ​​are referred to as parameter.

These parameters may be used in the function.

You can send any number of parameters, (,), separated by commas:

 

myFunction(argument1,argument2)

 

When declaring a function, the argument as a variable declaration:

function myFunction (var1, var2) 
{ 
Code 
}

Variables and parameters must appear in the same order. The first variable is the first parameter is passed a given value, and so on.

 

Function returns the value with

Sometimes we want the function to return the value of its local calling.

It can be achieved by using a return statement.

When using the return statement, the function stops execution and returns the specified value.

function myFunction()
{
 
     var x=5;
     return x;

}

The above function will return the value 5.

Note: The entire JavaScript does not stop execution, it is only a function .JavaScript will continue to execute code from where the calling function.

 

When you just want to quit the function, you can also use the return statement to return values ​​are optional:

function myFunction(a,b)
{
       if  (a>b)
       {
              return;
       }
       x=a+b
}

If a is greater than b, the above code will exit function, and does not calculate the sum of a and b.

 

Global JavaScript variable

Variables declared outside a function are global variables, all scripts and functions on the page can access it.

 

Local JavaScript Variables

In JavaScript variables declared inside a function (using var) is a local variable, so it can only be accessed inside the function. (Scope of the variable is local). You can use the same name as a local variable in different functions, because function only declared that variable in order to identify the variables.

As long as the function is completed, the local variable will be deleted.

Guess you like

Origin www.cnblogs.com/wzy123/p/11351876.html