This content originally appeared on DEV Community and was authored by rafikadir
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.
This content originally appeared on DEV Community and was authored by rafikadir
rafikadir | Sciencx (2023-06-05T13:19:52+00:00) 💻ES6 tutorial: const in javascript. Retrieved from https://www.scien.cx/2023/06/05/%f0%9f%92%bbes6-tutorial-const-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.