Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  6] [ 2]  / answers: 1 / hits: 25520  / 12 Years ago, tue, september 4, 2012, 12:00:00
1. >>> const a = 2
2. >>> var a = 3
3. >>> a = 4
4. >>> a // print 2


Why the operation line 3 is allowed? const seems more global than without any keyword...


More From » constants

 Answers
6

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.


[#83245] Monday, September 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annaliese

Total Points: 86
Total Questions: 97
Total Answers: 107

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;