Javascript const keyword context

1. >>> const a = 2 2. >>> var a = 3 3. >>> a = 4 4. >>> a // print 2 

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

+6
source share
2 answers

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

Creates a constant of 1, which can be global or local for the function in which it is declared. Constants follow the same scope rules as variables [.. and cannot share a name] with a function or variable in the same scope.

Firefox [..] throws a TypeError if you override 2 [which is different from re-assigning] with a constant. None of the major browsers produce any notifications or errors 2,3 if you assign a different value to the constant [..], but the redirection is not performed (only) in Firefox and Chrome (at least from version 20).

Note that const not part of the ECMAScript 5 specification, and the semantics of JavaScript 1.5 will be redefined in ECMAScript 6.

The behavior will vary across browser implementations regarding support semantics and re-declaration / re-assignment.


1 In IE 9, using const a = 2 leads to

"Syntax error"

2 In FF 14 const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a , when evaluated as one program, leads to

TypeError: override const a

which differs from the execution of each line differently in the REPL. I suspect this is because var aligned with const and because 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 const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a const a = 2; var a = 3; a = 4; a ratings to 2 without warning or message.

+9
source

const scope is defined as a "scope" (the scope of which is limited to the block in which it is declared).


MDN Documentation :

Constants are block -like, like variables defined using the let statement. The value of a constant cannot be changed by reassignment, and it cannot be redefined.

As for your specific question: first, as the comments said const relevant in ES6. I do not know about you, but I get (by typing your line 2: var a = 3; ): SyntaxError: The identifier 'a' has already been declared, so your example is not entirely possible.

+7
source

Source: https://habr.com/ru/post/1432387/


All Articles