JavaScript -- basic knowledge of functions

Posted by christh on Wed, 15 Sep 2021 09:20:33 +0200

1. Concept of function

Functions are also called function s and methods.

A function can encapsulate a piece of code. The encapsulated function has a special function. As a complete structure (function body), a piece of internally encapsulated code will be executed if it is to be executed, or it will not be executed if it is not executed.

2. Declaration (definition) of function

The function must be defined before it can be used, otherwise a reference error will occur.

Declaration syntax:

        Function function name (parameter){

                Encapsulated structure;

        }

//Define function
function fun() {
    console.log(2);
}

Function naming rules: it is composed of numbers, letters, underscores and $symbols. It cannot start with a number. It is case sensitive. Keywords and reserved words cannot be used.

When a function is declared, the function body will not be executed. Only when the function is called will it be executed.

3. Function call (function execution)

Calling method: function name ();

function fun() {
    console.log(2);
}
//Call function
fun();

The execution position of the internal statement of the function is independent of the position of the function definition and related to the position of the function call.

Functions can be defined once and executed multiple times.

4. Parameters of function

Interface: it is the parameter of a function. The parameter of a function is essentially a variable and can receive any type of data. As a result, the result of function execution is different according to different parameters.

A function can set 0 or more parameters, which are separated by commas.

The parameters of the function have different names according to the writing position:

Formal parameter: defines the internal parameter of (), which is called formal parameter. It is essentially a variable and can receive the data passed from the actual parameter, which is called formal parameter for short.

Actual parameters: the parameters inside the call () are called actual parameters. The essence is to pass various types of data to each formal parameter, which is called actual parameters for short.

function fun(a,b) { // a and b in parentheses are formal parameters
    console.log(a,b);
}
//Call function
fun(4,5);// 4 and 5 in parentheses are actual parameters

During the execution of the function, the parameter transfer process is accompanied by:

Generally, self encapsulated functions or functions encapsulated by others need to have an API interface description to tell the user what type of data needs to be passed and what functions to achieve

// Define a summation function and pass in two parameters
// Parameter: two parameters are passed. The data type is numeric
// Function: get the sum of two numbers
function sum(a,b) {
    console.log(a + b);
}
// In the calling function, add data inside the parentheses
sum(3,4);
sum("3",4);

5. Return value of function

Use a return keyword inside the function to set the return value of the function.

Function - 1: if a return keyword is executed in the internal structure of the function, the execution of the following code will be stopped immediately

// return to terminate the execution of the function
function sum() {
    console.log(1);
    console.log(2);
    console.log(3);
    return;
    console.log(4);
    console.log(5);
    console.log(6);
}
// Call function
sum();

Function - 2: you can add a space after the return keyword. Only a data literal or expression is defined after the space. After the function performs its own functions, the whole function will be transformed into an expression by return. The expression must find a value to continue to participate in the program. The value of the expression is the data after return

// Use the return value to make the result after the function runs
function fun(a,b) {
    return a + b;
}
// Call function
console.log(fun(3,4));

Return value application:

If a function has a return value, the execution result can participate in the program as ordinary data; or it can be assigned to a variable as ordinary data, or even to the arguments of other functions

// Use the return value to make the result after the function runs
function fun(a,b) {
    return a + b;
}

// Call function
console.log(fun(3,4));

// Assign the return value to the variable
var num = fun(3,4);
console.log(num);

// Assign the return value to the argument of the function
console.log(fun(2,fun(3,4)));

Note: if the return statement is not set for the function, the return value of the function is undefined; if return is set, but there is no value after return, the default return value is undefined.

6. Function expression

Is another way to define functions

Definition method: assign the definition of function and anonymous function (without function name) to a variable

The function expression is called by adding () to the variable name. It cannot be executed by adding () to the function name

// Define a function expression
var foo = function fun() {
    console.log(1);
};

// The method is actually adopted, because the variable name is used in the call
var foo2 = function() {
    console.log(2);
};

// When calling a function expression, it can only be called with a variable name. The function name call is unsuccessful
foo();
foo2();

7. Data type of function

Function is a separate data type function. You can participate in other programs

For example:

  • You can use the function as a parameter of another function and call it in another function.
// A function is a data type that can be used as an argument to other functions
setInterval(function() {
    console.log(1);
}, 1000);
  • You can treat a function as the return value of another function
// Treat a function as the return value of another function
function fn(b) {
    var a = 10;
    return function() {
        alert(a + b); 
    }
}

8. arguments object (built-in property of function)

All functions have a built-in arguments object. All arguments passed are stored in the arguments object.

arguments is a pseudo array, so it can be traversed.

The number of arguments and formal parameters of the function can be increased, and all arguments are stored in the arguments object.

// When calling a function, the number of arguments can be different from the formal parameters

//There is an arguments object inside the function, which will receive all the arguments
function fun() {
    console.log(arguments);
    console.log(arguments.length);
    // Each argument can be obtained using the array traversal method
    for(var i = 0; i <= arguments.length-1; i++) {
        console.log(arguments[i]);
    }
}

// Call function
fun(1,2,3,4,5,6,7);

Case application: define a summation function. If one parameter is passed in, it will return itself. If two parameters are passed in, it will return their sum. If three parameters are passed in, first compare the size of the first two parameters. The larger parameter will be summated and returned with the third parameter. If four or more parameters are passed in, an error prompt will be output.

function sum(a,b,c) {
    // Conditional branch statements take different branches according to the number of arguments
    switch (arguments.length) {
        case 1:
            return a;
            break;
        case 2:
            return a + b;
            break;
        case 3:
            return a > b ? a + c : b + c;
            break;
        default:
            // Prompt the user that the number of arguments is wrong
            // Analog console error
            throw new Error("The number of parameters cannot exceed 3");
    }
}
// Call function
console.log(sum(1));
console.log(sum(1,2));
console.log(sum(1,2,3));
console.log(sum(1,2,3,4,5));

9. Function recursion

The way in which a function can call itself through the function name is called function recursion.

More often, recursion is used to solve some mathematical phenomena. Too many times of function recursion will lead to errors: exceeding the maximum computing power of the computer

/* Function, if the parameter passed in is 1, it returns 1. If the parameter passed in is more than 1
 Number, let it return the parameter + the previous item of the function call */
function fun(a) {
    if (a === 1) {
        return 1;
    } else {
        return a + fun(a - 1);
    }
}
// Call function
console.log(fun(1));
console.log(fun(2));
console.log(fun(3));

console.log(fun(100000000000)); //Error reporting: exceeding the maximum computing power of the computer

Case application: output the value of a certain item of Fibonacci sequence

// Fibonacci sequence: the latter data is the sum of the first two data. 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
// Parameter: positive integer
// Return value: the value of Fibonacci sequence at the corresponding integer position
function fibo(a) {
    // a represents the number of items
    if (a === 1 || a === 2) {
        return 1;
    } else {
        // Returns the previous and previous items
        return fibo(a - 1) + fibo(a -2);
    }
}
// Call function
console.log(fibo(1));
console.log(fibo(2));
console.log(fibo(3));
console.log(fibo(4));
console.log(fibo(5));

10. Scope: the scope within which a variable can work

If a variable is defined inside a function, it can only be accessed inside the function. This variable cannot be used outside the function. The function is the scope of the variable definition.

Local variable: a variable defined inside a function and can only be accessed within the scope of the function.

Global variable: in a broad sense, it is also a local variable. It is defined in the global variable. The scope is global and can be accessed anywhere in the whole JavaScript program.

// Define function
function fun() {
    var a = 1;
    console.log(a);
}
// Execution function
fun();
// Function external call a
console.log(a); //Unsuccessful


// The parameters of a function are also local variables
function sum(a) {
    a = 2;
    console.log(a);
}
// Call function
sum(1);
console.log(a); //Unsuccessful

// Functions also have their own scopes
function outer() {
    var a = 1;
    function inner() {
        console.log(2);
    }
    // Only by calling a child function inside the function can it succeed
    inner();
}
// Call function
outer();
inner(); // The scope of error mode definition is inside the function

Local variables are destroyed after exiting the scope, and global variables are destroyed only when the web page or browser is closed.

Function parameters are also local variables,   It can only be used inside the function, and there is no definition outside the function.

A function also has its own scope, which defines the scope within which it can only be accessed within this scope, except that the scope cannot be accessed.   The function is defined inside another function. If the external function is not executed, it is equivalent to that the internal code is not written.

11. Scope chain

  If all such scopes are listed, there can be a structure: a chain structure pointing outside the function within the function. It is called scope chain.

function f1() { 
    function f2() {

    } 
} 

var num = 456; 

function f3() { 
    function f4() {

    } 
}

Illustration:

Masking effect: when the program encounters a variable, the search order of the scope is used. Variables with the same name may be defined in functions at different levels. When a variable is used, it will first find the variable from the scope of its own layer. If there is no variable definition in the current layer, it will search from this layer to the outside in order until the first variable definition is found. In the whole process, the inner variable will mask the outer variable, which is called "masking effect".

// global scope
var a = 1;
// Create function
function outer() {
    var a = 2;
    // Internal function
    function inner() {
        var a = 3;
        console.log(a);
    }
    inner();
}
// call
outer();

Effect of not writing var keyword

If you want to define a new variable inside the function, if you do not add the keyword VaR, it is equivalent to the defined global variable. If the global has the same identifier, it will be affected by the variables inside the function, and the local variables pollute the global variable. Therefore, you must write the var key every time you define a variable.

12. Pre analysis

  The execution of JavaScript code is performed by the JavaScript parser in the browser. When the JavaScript parser executes JavaScript code, it is divided into two processes: pre parsing process and code execution process.

Pre parsing process:

         1. Promoting the declaration of a variable to the front of the current scope will only promote the declaration, not the assignment.

         2. Raising the function declaration to the front of the current scope will only raise the declaration, not the call.

         3. Raise var first and then function.

JavaScript execution process: after pre parsing, execute js code from top to bottom according to the established rules according to the new code order.

Lifting sequence:

  • In the pre parsing process, the var variable declaration is raised first, and then the function function declaration is raised.
  • Assuming that the variable name and function name are the same, the later promoted function name identifier will overwrite the first promoted variable name. When the call identifier appears in the subsequent code, the internal function definition process is not undefined.
  • If the process of calling the identifier is behind the source code function and variable definition, which is equivalent to that the function name overwrites the variable name once, and the new value overwrites the function value when the variable assignment is executed, then the identifier is called again later, using the new value stored in the variable.
  • Suggestion: do not write the same identifier to the variable name or function name to avoid overwriting.

  The function expression is used to promote the variable declaration. After the promotion, an undefined variable is stored inside the variable. In the previous function method call, the data type will prompt an error.   Suggestion: when defining a function, you'd better use the function keyword to define it, so that the function declaration promotion can take effect forever.

// Pre parsing elevates variables and function declarations to the top of the scope
//Simulated lifting
// var a; / / equivalent to storing an undefined value
// function fun() {
//     console.log(2);
// }
// Call a variable
console.log(a);
console.log(fun);
// Post definition variable
var a = 1;
// a = 1;
var fun = "haha";
//Call the function first
fun();
// Define function
function fun() {
    console.log(2);
}
// call
fun();


foo();
// Function expressions promote variable declarations
var foo = function () {
    console.log(a);
}

13,   IIFE self calling function

  IIFE: immediately invoked function expression, which is called the function expression of immediate call, also known as self calling function. It means that the function is called immediately when it is defined.

  Function calling method: add () operator after the variable name of function name or function expression.

  The method of dwarfing a function into an expression allows the function to participate in some operations, that is, add some operators in front of the function.

         Mathematical operators: + - ()

         Logical operator:! Non operation

//Keyword definition cannot be executed immediately
// function fun() {
//     console.log(1);
// }();

//Function expression mode, which can be executed immediately after definition
var foo = function () {
    console.log(2);
}();


//By adding operators in front of functions, functions can be dwarfed into expressions
+ function fun() {
    console.log(1);
}();
- function fun() {
    console.log(1);
}();
(function fun() {
    console.log(1);
})();
!function fun() {
    console.log(1);
}();
// IIFE pays attention to the scope of the function, and can't call the function fun ();

//Common IIFE structure
(function(a){
    console.log(a);
})(4);

  IIFE structure can close the scope of a function, and functions cannot be called outside the structure.

  The () operator is most commonly used in IIFE, and functions can use anonymous functions without writing function names.

Topics: Javascript html5