Create function

1. Create an ordinary function

function function name () {

    Function body; // encapsulated code


Function name (); // call function

function getSum () {
    for ( var i = 1, sum = 0; i <= 100; i ++ ) { 
      sum + = i; 
   console.log (sum); 
getSum ();   // working function

2. Create a function with parameters

 function function name (parameter) {// used to receive the passed data

    Function body


Function name (parameter); // The data actually passed

Note : The parameter when creating a function is called a formal parameter, and the parameter when calling a function is called an actual parameter.

function getSum(n){
   for(var i=1,sum=0;i<=n;i++){

3. Create a function with a return value

 function function name (parameter) {

    Function body

    return value; // Return value, return the result after the function is executed


Function name (parameter);

Note : return is used to return the execution result of the function. If there is no return in the function body or no return value is returned after return, undefined is returned. After the return is executed, the remaining code in the function body is no longer executed.

function getMax(a,b){
    return a;
    return b;
var r=getMax(5,9);


Guess you like