const keyword scope in Javascript

后端 未结 2 847
感情败类
感情败类 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

    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.

提交回复
热议问题