Function declaration statement
Use the function keyword, followed by a set of parameters and the function body
function funcname([arg1 [,arg2 [...,argn]]]){ statement; }
funcname is the identifier of the function name to be declared. The parameter list is enclosed in parentheses after the function name, separated by commas. When calling a function, these identifiers refer to the actual parameters passed into the function
[Note] The curly braces in the function statement are required, which is the same as the statement block used in while loops and other statements. Differently, even if the function body contains only one statement, it must still be enclosed in curly braces
function test()//SyntaxError: Unexpected end of input function test(){};//不报错 while(true);//不报错
Promotion
In the third article of the scope blog series, function declarations were mentioned Hoisting, the function name and function body are hoisted
foo(); function foo(){ console.log(1);//1 }
The reason why the above code snippet can output 1 on the console is because the foo() function declaration is hoisted, as shown below:
function foo(){ console.log(1); } foo();
Duplication
The repeated declaration of a variable is useless, but the repeated declaration of a function will overwrite the previous declaration (whether it is a variable or a function declaration)
//变量的重复声明无用var a = 1; var a; console.log(a);//1
//由于函数声明提升优先于变量声明提升,所以变量的声明无作用 var a; function a(){ console.log(1); } a();//1
//后面的函数声明会覆盖前面的函数声明 a();//2 function a(){ console.log(1); } function a(){ console.log(2); }
Therefore, you should avoid using the same Duplicate declarations in the scope
Delete
Like variable declarations, variables created by function declaration statements cannot be deleted
function foo(){ console.log(1); } delete foo;//false console.log(foo());//1
The above is the detailed content of Detailed explanation of function declaration, promotion, duplication and deletion examples of the basics of javascript functions. For more information, please follow other related articles on the PHP Chinese website!