Javascript variable Declaration

Source: Internet
Author: User

Zhuanzi: http://qingbob.com/blog/%E8%B0%88javascript%E5%8F%98%E9%87%8F%E5%A3%B0%E6%98%8E

I encountered an interview question in my previous interview.

 
VaRA=10;(Function(){Console.Log(A);VaRA=20;})()
    • Just 5 linesCodeWhat is the log result?
    • IfVaR A = 20;AndConsole. Log ()What about statement order reconciliation?

The answer to this question isUndefined. Not 10.

The key is that the Javascript variable Declaration has a hoisting mechanism, and the variable declaration will always be promoted to the top of the scope (note that the test is only a declaration and has not been assigned a value ). In fact, the preceding statement is equivalent:

 
VaRA=10;(Function(){VaRA;// Declare the variable hoisting first.Console.Log(A);A=20;// Assign another value})()

A little more simplified:

Bla=2VaRBla;// This is a split line, and the effects of upstream and downstream code are the sameVaRBla;Bla=2;

That is, use it first and then declare it (note that the declaration has not been assigned a value). In this way, the declaration and value assignment are separated. Therefore, we recommend that you declare the variables you need at the top of the function.

Likewise, we can understand that the following code also reports an error.

F()// It is obvious that this error occurs because f has not been assigned a function.VaRF=Function(){Console.Log("Hello");}

But there is a problem. If I modify the function declaration in the above example F, will it still report an error?

F()// Can it be run?FunctionF(){Console.Log("Hello");}

Here I want to emphasize the two types of function declarations.VaR F = function (){}AndFunction f (){}Difference.

In fact, all function declarations in JavaScript (Function declarations) And variable Declaration (Variable declarations) Will be promoted to the top of their scope. Note that there is only one function Declaration, that isFunction f (){}. WhileVaR F = function (){}What is it? You can think of it as assigning an anonymous function (you can also take the function name, which will be explained below) to a variable.

In the above two examples, we also want to implement the effect of first use and then definition. Only the second method is useful. Although function f is defined after it is used, in the javascript interpreter, it is still defined before the execution statement.

In the first example, the execution result is as follows:

VaRF;F()// No function is defined and cannot be executed.F=Function(){Console.Log("Hello");}

In this case, although JavaScript allows execution before declaration,But do not do this. Please follow the good habit of declaring and then using it.

Let's look at another situation. If I define the previous function

 
VaRF=Function(){};
    1. Add the function name to the anonymous function on the right.
    2. Execute a function using the function name on the right
    3. Can it be successful?
 
VaRF=FunctionAB(){};AB();

The answer is no, because the above Code defines the f functionNamed function expressions)Instead of the real function declaration,Note that this function name is only useful in the function scope.. The following code fully demonstrates its significance:

VaRF=FunctionFoo(){ReturnTypeofFoo;};TypeofFoo;// "Undefined"F();// "Function"

So what is the significance of such a statement? Well, as far as the information I have found, the advantage of doing so is that it is easy to debug.

Next, consider some unexpected edges, although I thinkProgramWriting the following code is a bit difficult and should be avoided in practice, but it is worth mentioning as a question of the exam. For example, compare the following two pieces of code:

  function   value   () {  return   1  ;  }  var   value  ;   alert   (  typeof   value   );   // "function"  
FunctionValue(){Return1;}VaRValue=1;Alert(TypeofValue);// "Number"

What I want to explain in the first code is:The function declaration overwrites the variable declaration.Note that the declaration has not been assigned a value. For example, in the Code, although the variable with the same name is declared again after the function, the result of typeof is still function

The second part of the code is as follows:Function declaration does not overwrite variable assignment or Initialization, As shown in the code.

Name resolution order

Why is the above result? Why does the function declaration overwrite the variable declaration. This is because name resolution order. I don't know how to translate this term.Name Resolution SequenceRight.

In JavaScript, a variable name can enter the scope in four ways.

    • Language built-in, All scopes haveThisAndArgumentsKeywords
    • Format parametersFunction parameters are valid throughout the scope.
    • Function Declaration
    • Variable Declaration

The four orders listed above are the order of the highest priority (I keep this in mind. The test result is that the priority of parameters and functions is higher than that of built-in languages. You can name the formal parameter arguments or define a function named arguments, the built-in argument of the result is overwritten.), Once a variable name has been declared, it cannot be overwritten by other lower-priority variable declaration forms.

ReferenceArticle:

    • Named function expressions demystified
    • Function-declarations-vs-function-expressions
    • Javascript scoping and hoisting
    • Answering baranovskiy's JavaScript quiz
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.