const keyword scope in Javascript

后端 未结 2 837
感情败类
感情败类 2020-12-11 15:47
1. >>> const a = 2
2. >>> var a = 3
3. >>> a = 4
4. >>> a // print 2

Why the operation line 3 is allowed? const

相关标签:
2条回答
  • 2020-12-11 16:38

    This is is just how const works (or doesn't work):

    Creates a constant1 that can be global or local to the function in which it is declared. Constants follow the same scope rules as variables [.. and cannot share a name] with a function or a variable in the same scope.

    Firefox [..] throws a TypeError if you redeclare2 [which is different than re-assigning] a constant. None of the major browsers produce any notices or errors2,3 if you assign another value to a constant [..] but the reassignment is unsuccessful (only) in Firefox and Chrome (at least since version 20).

    Note that const is not part of the ECMAScript 5 specification and the JavaScript 1.5 semantics will be re-defined in ECMAScript 6.

    Behavior will vary across browser implementations with respect to support and re-declaration/re-assignments semantics.


    1 In IE 9, using const a = 2 results in

    "Syntax error"

    2 In FF 14, const a = 2; var a = 3; a = 4; a, when evaluated as a single program, results in

    TypeError: redeclaration of const a

    which is different than executing each line one-at-a-time in the REPL. I suspect this is because var is hoisted above the const and because a const "cannot share a name with a function or variable in the same scope".

    3 In Chrome 21, const a = 2; var a = 3; a = 4; a evaluates to 2 with no warning or message.

    0 讨论(0)
  • 2020-12-11 16:38

    const scope is defined as 'block scoped' (the scope of which, is restricted to the block in which it is declared).


    MDN documentation:

    Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.

    Regarding your specific issue: First as comments said const is relevant in ES6. I don't know about you but i get (typing your line 2: var a = 3;): SyntaxError: Identifier 'a' has already been declared so your example is not quite possible.

    0 讨论(0)
提交回复
热议问题