💻ES6 tutorial: const in javascript
In JavaScript, the const
keyword is used to declare a constant, which is a variable that cannot be re-assigned after it is initialized. Constants are block-scoped, meaning they are only accessible within the block where they are defined.
- Declaration and Initialization: Constants are declared using the
const
keyword, followed by the variable name and an optional initializer (value assignment). Once a constant is declared and assigned a value, its value cannot be changed.
const x = 10;
const x = 10;
// Identifier 'x' has already been declared
- Block Scoping: Constants are block-scoped, just like variables declared with
let
andvar
. This means that they are only accessible within the block in which they are defined.
if (true) {
const message = "Hello!";
console.log(message); // Output: Hello!
}
console.log(message); // Error: message is not defined
- Immutable Value: The value assigned to a constant cannot be changed or re-assigned. However, for complex data types like objects and arrays, the properties or elements of the object or array can still be modified.
const pi = 3.14;
pi = 3.14159; // Error: Assignment to constant variable.
const person = { name: "John", age: 30 };
person.name = "Jane"; // Valid: Modifying the property of the object.
person = { name: "Jane", age: 25 }; // Error: Assignment to constant variable.
- Hoisting: Like variables declared with
var
, constants declared withconst
are also hoisted to the top of their scope. Using aconst
variable before it is declared will result in aReferenceError
console.log(pi); // Output: ReferenceError: Cannot access 'pi' before initialization
const pi = 3.14;
console.log(pi); // Output: 3.14
- Block-Level Re-declaration: Constants cannot be re-declared within the same block scope. Attempting to re-declare a constant within the same block will result in an error.
if (true) {
const x = 10;
const x = 20; // Error: Identifier 'x' has already been declared
}
The const
keyword is commonly used for values that are not intended to be changed, such as mathematical constants or configuration settings. It helps ensure the immutability of important values in your code, improving code readability and reducing bugs caused by accidental re-assignment.
Subscribe to my newsletter
Read articles from Rafi kadir directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Rafi kadir
Rafi kadir
Hello, I am Rafi kadir and I am from Bangladesh. Taking Web Development as a profession not only fulfills my pocket but also my heart because it has been my passion since my early teenage.