First, the concept
1. Variable declaration
In JavaScript, variables are generally declared by means of the var keyword (except the implicit declaration, the Let keyword Declaration), which declares a,b,c three variables (and assigns a value to a) by using the var keyword:
var a=1,b,c; Keyword explicitly declares a variable a,b,c and assigns a value to a
Console.log (a); 1
Because B,c does not define a variable type, it outputs "undefined"
Console.log (b); Undefined
Console.log (c); Undefined
If the variable is not declared, the output is not declared error message
Console.log (d); Uncaught referenceerror:d is not defined (...)
2. Function declaration
In JavaScript, functions are generally declared directly through the keyword function (except for anonymous functions). Declare an a function as follows by the function keyword:
function A () { //... .. }
Console.log (a); function A () {//...}
Second, the difference
In the execution mechanism of JavaScript (pre-compilation phase), variable declarations and function declarations have precedence, and function declarations have precedence over variable declarations . If you declare a function and a variable, the function name and the variable name are the same, the declared variable is not valid, and by typeof we can see that, regardless of the order of declaration, if a function and a variable with the same name are declared, only the declared function is valid and the declared variable is invalid (equivalent to a function with the same name overrides the variable) As shown in the following code:
varA;functionA () {//......}alert (typeofa);//function//the declaration order is the same as the result.functionA () {//......}varA;alert (typeofa);//function, the equivalent of the declared variable A is covered by the
If you assign a value to variable a directly in the above scenario (JavaScript precompilation stage), the following result
function A () {
//...... }var a = 1;alert (typeof a); Number, because this is when JavaScript enters the code interpretation execution phase. Variable A is assigned a value of 1, so the output is number type
Iii. references
- Pre-parsing of JavaScript variables and function declaration in advance
- Scope Cheatsheet
- Detailed description of JavaScript execution sequence
Note on JavaScript declaring variables and function keywords through the var keyword