Course Content
Introduction to JavaScript
Introduction to JavaScript
const
Another way to define a variable in JavaScript is using the const
keyword. The primary difference between let
and const
is that variables created using const cannot change their values, whereas using the let
keyword allows changes to the variable's value.
Let's compare the behavior of variables using let
and const
. Take a look at the following example where we can change the value of the a
variable:
// A variable changing let a = 5; console.log(a); // Print the initial value of `a` a = 10; console.log(a); // Print the updated value of `a`
In contrast, let's examine the behavior of the b
variable. We will encounter an error: TypeError: Assignment to a constant variable.
// A constant cannot be changed const b = 7; console.log(b); // Print the initial value of `b` // Attempting to reassign a `const` variable will result in an error b = 8; // This line will throw an error: "TypeError: Assignment to constant variable." console.log(b);
Usage
Constants are used as immutable variables. You can define a constant once and use it multiple times.
Constants provide data integrity while allowing for quick refactoring.
Note
Refactoring involves making structural changes to the code, such as modifying values, variable/function names, and more.
For example, consider maxHeight
for site elements. You can release a site update by changing the maximum height of elements with just one modification in the code. However, it's important to note that you cannot change the maximum height during runtime, ensuring data integrity.
const maxHeight = 250; console.log(maxHeight - 15); console.log(maxHeight - 12); console.log(maxHeight - 5); console.log(maxHeight - 13); console.log(maxHeight - 22); console.log(maxHeight - 52);
Thanks for your feedback!