What's the difference between variable definition and declaration in JavaScript?

后端 未结 8 1401
情话喂你
情话喂你 2020-12-03 03:54

Is this a variable definition or declaration? And why?

var x;

..and is the memory reserved for x after this st

8条回答
  •  佛祖请我去吃肉
    2020-12-03 04:06

    > var x;
    undefined
    > x
    undefined // now it looks like x is defined to the value undefined
    > y
    ReferenceError: y is not defined
    

    Although it is usually said that Javascript is an interpreted language, but there is also a compilation step that happens very fast just before the interpreter runs. The job of this compilation step is to create scope chains, where variables are declared(no read/write operation here, just simple name-keeping) in their respective scopes. These variables will point to some memory location but value in it will be undefined until some execution is carried out by the interpreter.

    > Compiler run:

    When compiler sees var x;, it will simply book-keep this variable in its respective scope.

    The next x; and y; are simply ignored in the compilation step as they are execution statements.

    > Interpreter run:

    When interpreter sees var x;, it will skip this as there is no read/write operation here.

    Now when interpreter sees x;(execution statement), "x" will already be declared in the scope, and it will hold value "undefined", which is what you get on the console.

    But when interpreter sees y; similarly, there has been no previous declaration or name-keeping for it in the compilation step, and thus we get the ReferenceError as expected.

    Hope someone finds this comment useful.

提交回复
热议问题