Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const keyword scope in Javascript

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...

like image 513
JohnJohnGa Avatar asked Sep 04 '12 23:09

JohnJohnGa


People also ask

What is the scope of const in JavaScript?

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.

Does const have function 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.

Does const have global scope in JavaScript?

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.

Is const a global scope?

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.


1 Answers

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.

like image 75
Mercury Avatar answered Oct 17 '22 08:10

Mercury