1. Introduction
In this tutorial, we’ll discuss another way of declaring block-scoped constants – const
. A const
is similar to let
with respect to scope.
A const
is block-scoped and can not be redeclared or reassigned a new value once declared or initialized.
When you use a const
to hold an array or an object it means you are making to what it points to a constant. It means you can’t assign a new array or an object. However, you can still change the properties of the object or elements of an array.
const x = 1; x = 2; //TypeError: Assignment to constant variable. const x = 3; //SyntaxError: Identifier 'x' has already been declared
const
does not mean the value it holds is immutable.
Whatever we know about Temporal Dead Zone (TDZ) with respect to let
applies to const
as well.
2. Convention to declare let
The convention is to use capital letters for constants.
const MESSAGE = 'hello world';
3. Scope of const
Constants are block-scoped. It means they can be accessed within the block they are declared as well as in the blocks contained in the block. If you redeclare the constant in the inner block, it doesn’t affect the constant in the outer block.
const x = 1; { const x = 2; console.log("x inside block: " + x); } console.log("x outside block: " + x);
4. const
doesn’t add to window
object
Unlike var
, global constants do not become properties of the window
object.
const x = 5; console.log(window.x); // undefined
5. const
need to be initialized
Constants are need to be initialized. You’ll get error if you don’t do it.
const x; //SyntaxError: Missing initializer in const declaration
6. const
hoisting
Constants declared with const
are also hoisted but, unlike var
, are not initialized with a default value. If you try to read a const
before it is initialized, you’ll get an exception.
console.log(x); //ReferenceError: Cannot access 'x' before initialization const x = 5;
7. Can’t have function with same name as constant in same scope
const test = 5; function test() {} // SyntaxError: Identifier 'test' has already been declared
8. Using const
with array
When you declare a const
to hold an array, it means you are creating a read-only reference to the value. Value here is the array. You can change the elements of the array but you can’t assign a new array.
const arr = [1, 2]; const arr = [3, 4]; // SyntaxError: Identifier 'arr' has already been declared arr[0] = 5; // OK
9. Using const
with object
Similar to using const
with an array, you can not assign a new object to a const
but you can change the properties of the object. Using const
with object will not make it immutable.
const PERSON = { name: “James” };
PERSON.name = “Sunny”; // OK
PERSON = {}; // TypeError: Assignment to constant variable.
10. Conclusion
In this tutorial, we discussed how to declare and use constants. Understanding of let
, var
and const
is required for being a good JavaScript developer.