In Node.js (and in JavaScript in common), const is a keyword which is used to define read-only variables. A variable that has been declared with const cannot be assigned a new value. This is especially helpful with data that should remain fixed in the whole program e.g configurations, imports, fixed values and so on.
As per the above statement this is how const will react in a node application An example would be:
1. Constant Binding: The binding (or reference in normal terms) of a variable declared using the const keyword cannot be modified meaning the variable cannot be assigned with a new value.
javascript
const x = 10;
x = 20; // An exception will be thrown here.
2. Immutable Binding not Value: const makes the binding immutable but the elements of objects and arrays assigned to const may be changed. So in other words, if there is a const variable which refers to an object or an array, then that object or array can be altered in terms of its properties or index.
javascript
const person = { name: 'xyz', age: 25 };
person.age = 26;
console.log(person.age);
3. Block Scope: Just like let, const has a block scope meaning it can only be referenced within the parenthesis depicted where the variable is defined.
javascript
if (true) {
const greeting = "Hello";
console.log(greeting);
}
console.log(greeting);
When to Use ‘const’ in Node.js
- It is suggested to declare const for fixed values such as configuration values or imported modules which are not meant to change.
- It is also useful in preventing rewrites of the variable making the code neater and less buggy.