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...
The scope of a const variable is block scope. It can be updated and re-declared into the scope. It can be updated but cannot be re-declared into the scope. It cannot be updated or re-declared into the scope.
Hoisting of const var declarations are globally scoped or function scoped while let and const are block scoped. var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
The const Keyword Functionally const is similar to let and var in that it declares variables. It is also just like let in that it has block level scope that can be global or local to the function in which it is declared.
You just use const at global scope: const aGlobalConstant = 42; That creates a global constant. It is not a property of the global object (because const , let , and class don't create properties on the global object), but it is a global constant accessible to all code running within that global environment.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With