Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Const in JavaScript allows you to modify only the value of the array, but the reference to the array cannot be changed. The javascript const variable creates only reference to the value.
The const keyword in JavaScript is used to declare variables whose values should not be reassigned after their initial assignment.
It stands for constant, indicating that the value it holds is constant post declaration. Here’s a simple example:
const pi = 3.14;
In this case, pi is a constant variable that holds the value of 3.14, and any attempt to reassign a new value to pi will result in an error.
What is const in JavaScript?
In JavaScript, const is a keyword used to declare a variable with a constant (unchangeable) value. Once a variable is assigned a value using const, that value cannot be reassigned or changed throughout the program's execution. It provides a way to create variables that are meant to be read-only.
Let's understand the core concepts of using const in JavaScript.
Syntax of const
The const keyword is used for declaring variables that won't be reassigned to new values. The syntax is pretty straightforward but understanding its use cases is essential for effective JavaScript coding.
const variableName = value;
Here, const is the keyword.
variableName is the name you are giving to the variable.
value is the initial value you are assigning to the variable.
In JavaScript, const creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned.
Example
Javascript
Javascript
const daysInWeek = 7;
console.log("Days in the week are: "+ daysInWeek);
You can also try this code with Online Javascript Compiler
In this example, daysInWeek is a constant representing the number of days in a week. The attempt to modify the value of the constant will result in an error, showcasing the immutability feature of const.
Output:
Importance of const
The const keyword plays a vital role in promoting good coding practices by ensuring variable non-reassignability. This characteristic is crucial for preventing bugs that could arise from accidental variable reassignment, thus making the code more predictable and easier to read and debug.
Immutability vs. Non-reassignability
These two concepts are critical and often create confusion when working with const in JavaScript.
Non-reassignability
const creates a variable name identifier that cannot be reassigned to a different value. However, if the value is an object, the properties of the object can still be modified.
JavaScript Code
JavaScript Code
const person = {
name: "Alice"
};
person.name = "Bob"; // This is fine
console.log(person.name);
You can also try this code with Online Javascript Compiler
person = {name: "Charlie"}; // Error: Assignment to constant variable.
In the above example, although person is a const, the name property of the object it references is mutable.
Immutability
Immutability is a broader concept. An immutable object is an object whose state cannot be modified after it is created. In JavaScript, primitive values like numbers, strings, and booleans are immutable, but objects and arrays are mutable.
const age = 30;
// age = 31; // Error: Assignment to constant variable
JavaScript Code
JavaScript Code
const numbers = [1, 2, 3];
numbers.push(4); // This is fine
console.log(numbers);
You can also try this code with Online Javascript Compiler
In the first scenario, age is a primitive value, and const ensures it remains assigned to 30. In the second scenario, numbers is an array, and while const prevents reassignment, it doesn't provide immutability; the array can still be modified.
These concepts underline the importance of understanding the behavior of const in different contexts. It's not just about preventing reassignment but understanding how it interacts with the data types in JavaScript. It’s a crucial part of writing predictable, bug-free code.
Common Use Cases
Declaring Constants
The const keyword is perfect for declaring constants, values that will never change over the program's execution.
JavaScript Code
JavaScript Code
const EARTH_RADIUS_KM = 6371;
console.log(EARTH_RADIUS_KM);
You can also try this code with Online Javascript Compiler
Here, SERVER_CONFIG is a configuration object that holds server settings, and using const ensures that these settings aren't altered later in the code, which could introduce bugs.
Loop Variables
When working with loops, especially those iterating over fixed sets of values, const can be useful.
JavaScript Code
JavaScript Code
const NUMBERS = [1, 2, 3, 4, 5];
for(const number of NUMBERS) {
console.log(number); }
You can also try this code with Online Javascript Compiler
Here, the computeArea function reference is declared with const, indicating that it should not be reassigned later in the program.
Advanced Usage of const
const with Object.freeze():
The const keyword in JavaScript ensures that the identifier cannot be reassigned. However, if the identifier refers to an object, the properties of that object can still be modified. In contrast, Object.freeze() is a method that prevents the modification of existing properties values and the addition of new properties to an object.
Combining these two can create a pattern of deeper immutability:
JavaScript Code
JavaScript Code
const person = Object.freeze({
name: "Alice",
age: 30
});
person.name = "Bob"; // This will fail silently or throw an error in strict mode
console.log(person.name);
You can also try this code with Online Javascript Compiler
In the above code snippet, the person object is both a constant and frozen, which prevents any modification to the object. This can be especially useful in situations where data integrity is crucial, such as configuration data.
Real-world Applications of const
Configuration Objects
Projects often require certain configurations to be set and unchanged throughout the runtime of the application. Utilizing const for this purpose can ensure these configurations remain intact.
In the above snippet, config is an object holding configuration data that is used in a fetch request. This setup ensures that the configurations are read-only, promoting consistency throughout the application.
Redux Reducers
Redux, a popular state management library in JavaScript applications, often employs const for defining action types, which are crucial for the reducer functions to understand the actions to be performed.
In this expanded example, action types ADD_ITEM and REMOVE_ITEM are defined using const, ensuring they remain unmodified. The todoReducer function then uses these constants to understand the action types and modify the state accordingly.
Common Issues and Solutions (Extended)
Reassignment Error
One of the most common errors when using const is attempting to reassign its value after declaration. The following code snippet demonstrates this error:
const number = 42;
number = 50; // Uncaught TypeError: Assignment to constant variable.
Solution: To avoid this error, use let if you anticipate the need to reassign the variable in future:
let number = 42;
number = 50; // No error, the variable is reassigned successfully
Assignment Without Initialization
Unlike var and let, const requires an initializer. A const declaration without initialization will result in a syntax error:
const number; // Uncaught SyntaxError: Missing initializer in const declaration
Solution: Always provide an initial value when declaring a const variable:
const number = 42; // No error
Best Practices
When to use const
Immutable Values: Use const for values that should remain unchanged throughout the program execution. This signifies the intent that the value should not be modified, making the code more readable and predictable.
const PI = 3.14159;
Object References: When working with objects, using const ensures that the reference to the object remains constant. This is useful in scenarios where the reference should remain intact, but the object's properties may be modified.
Use const for variables whose value should not be reassigned. It ensures immutability for primitive values and prevents reference reassignment for objects.
What is let and const in JavaScript?
let is used for block-scoped, reassignable variables, while const declares block-scoped variables whose value or reference cannot be reassigned.
What is const in a function?
const in a function ensures that the variable defined cannot be reassigned within the function, often used for constants or references.
Conclusion
We delved deep into the const keyword, exploring its syntax, usage scenarios, and its role in maintaining data integrity in JavaScript applications. Through examples, we demonstrated common issues and provided solutions to ensure smooth development experience. We also discussed best practices, ensuring a clear understanding of when and how to use const effectively in different scenarios. This exploration sheds light on the importance of const in promoting good coding practices and creating reliable, maintainable JavaScript code.