Function knowledge points of JS

Keywords: less

I. defining functions

1. Function declaration method

function sum(a, b) {
    console.log(1+3);
    }
    sum(10, 20);

2. Functional expression

var add = function () {
    console.log(1+3);
    };
    add();

3. Use Function constructor

var add2 = new Function('console.log(1+3);');
    add2();

In the process of parameter transfer, it is not allowed to transfer less parameters, so the system will report an error.

 function sum(num1, num2) {
    console.log(num1 + num2);
    num1 = 0;
    num2 = 0;
    }

    sum(100);

A good method to get arrays when the number of arrays is uncertain (can be used directly)

function sum(num1, num2,num3) {
    // arguments object
    // console.log(arguments);
    var value = 0;
    for(var i=0; i < arguments.length; i++){
    value += arguments[i];
    }
    console.log(value);
    console.log(arguments.length);
    console.log(sum.length);//Number of formal parameters
    if(arguments.length === sum.length){

    }
    }

    sum(10, 20, 30, 100, 200, 100, 20);

2. Callback function (recursion), that is, continue to call the function inside the function

function fn(num1, num2, func) {
        return func(num1, num2);//func is the function name
    }


    // Addition, subtraction, multiplication and division function
    function add(a, b) {
        return a + b;
    }



    function sub(a, b) {
        return a - b;
    }

    function mul(a, b) {
        return a * b;
    }

    function divide(a, b) {
        return a / b;
    }

    console.log(fn(10, 20, add));//30
    console.log(fn(10, 20, sub));//-10
    console.log(fn(10, 20, mul));//200
    console.log(fn(10, 20, divide));//0.5

Local and global variables of functions

Variables without var are global variables. All variables with the same name can use their values. Variables with var inside a function are local variables, which can only be used inside a function.

Scope of function

In the execution process, first look for the scope in this scope. If you find it, you will not see the scope at a higher level.

    fun();
    function fun(){
        // Statement advance
        var num;
        console.log(num);//First, Num is found in this scope, but the value of num cannot be found because the variable declaration is advanced but the value declaration is not.
        num = 20;
    }

 

Posted by sathyan on Tue, 15 Oct 2019 13:05:04 -0700