There is a special type of variable in JavaScript, which is called constant.
A constant is a variable that we do not want to change the value of during the whole program.
Creation:
You create a const
variable just like you create a normal one, but using the word const
instead of let
:
const ourName = "AlgoCademy";
console.log(ourName); // Output: AlgoCademy
Reassignment not allowed:
However, a const
variable cannot be reassigned because it is constant. If you try to reassign a const
variable, you’ll get a TypeError
.
For example, this code:
const ourName = "AlgoCademy";
ourName = "Andy"; // Here is the problem
would produce TypeError: Assignment to constant variable
Must be initialized:
Constant variables must be initialized when declared. If you try to declare a const
variable without a value, you’ll get a SyntaxError
.
For example, this code:
const ourName;
would produce SyntaxError: Missing initializer in const declaration
Usage:
It seems like constants are just variables with some limitations. So, why use them when we can do the same things (and more) with normal variables?
The power of constants lies in their limitation! Constants were invented to provide some level of guarantee that the code can't change the underlying value.
This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.
Picture this: You are the first developer to have ever worked at a new startup. When you have written the core code, you created some important variables that describe your company:
const companyName = "Apple";
const foundingDate = "April 1st, 1976";
const founderName = "Steve Jobs";
Ten years later, your company blew up and you have hundreds of Software Engineers managing millions of lines of code.
I bet you wouldn't love it if a Junior Developer was able to do this successfully:
companyName = "Microsoft";
founderName = "Bill Gates";
But you are smart! You made those variables constants ten years ago and have nothing to worry about now. As for the Junior, they'll just get an error and probably a slap on the wrist by their manager.
Assignment
Follow the Coding Tutorial and let's work with constants!
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the concept of const
variables in JavaScript. Understanding how to use constants is crucial for writing robust and maintainable code. Constants are particularly useful in scenarios where you want to ensure that certain values remain unchanged throughout the execution of your program.
Constants in JavaScript are variables that, once assigned a value, cannot be reassigned. This immutability is what makes them "constant." To declare a constant, you use the const
keyword followed by the variable name and its value. Here is a simple example:
const pi = 3.14;
console.log(pi); // Output: 3.14
In this example, pi
is a constant that holds the value 3.14. Attempting to reassign pi
will result in a TypeError
.
Let's delve deeper into the key concepts and techniques related to constants:
let
.Here is an example demonstrating these concepts:
const maxUsers = 100;
if (true) {
const maxUsers = 50;
console.log(maxUsers); // Output: 50
}
console.log(maxUsers); // Output: 100
In this example, the maxUsers
constant inside the if
block is a different variable from the one outside the block, demonstrating block scope.
Let's look at some practical examples and use cases for constants:
const apiUrl = "https://api.example.com";
const maxRetries = 5;
function fetchData() {
for (let i = 0; i < maxRetries; i++) {
// Attempt to fetch data from apiUrl
}
}
In this example, apiUrl
and maxRetries
are constants that provide configuration values for the fetchData
function. These values should not change during the execution of the program.
Here are some common mistakes to avoid and best practices to follow when using constants:
TypeError
.SyntaxError
.While constants are immutable, the objects or arrays they reference can still be modified. Here is an example:
const user = { name: "Alice" };
user.name = "Bob";
console.log(user.name); // Output: Bob
In this example, the user
object itself is constant, but its properties can be changed. To make an object truly immutable, you can use Object.freeze
:
const user = Object.freeze({ name: "Alice" });
user.name = "Bob";
console.log(user.name); // Output: Alice
Here is a well-commented code snippet demonstrating the correct use of constants:
const companyName = "TechCorp";
const foundingYear = 2000;
// Function to display company information
function displayCompanyInfo() {
console.log(`Company: ${companyName}, Founded: ${foundingYear}`);
}
displayCompanyInfo(); // Output: Company: TechCorp, Founded: 2000
When debugging code that uses constants, keep the following tips in mind:
To test functions that use constants, you can write unit tests. Here is an example using a simple testing framework:
const assert = require("assert");
const companyName = "TechCorp";
function getCompanyName() {
return companyName;
}
// Test case
assert.strictEqual(getCompanyName(), "TechCorp");
console.log("All tests passed!");
When working with constants, consider the following strategies:
In this lesson, we covered the importance of constants in JavaScript, how to declare and use them, and best practices to follow. Mastering the use of constants will help you write more reliable and maintainable code. Keep practicing and exploring further applications of constants in your projects.
For further reading and practice, check out the following resources: