JavaScript Const

The const keyword in JavaScript is used to declare a constant variable. This means that the value of the variable cannot be changed once it has been assigned. This can be useful for preventing accidental changes to important variables in your code.

Declaring Const Variables

To declare a constant variable in JavaScript, you use the const keyword followed by the variable name and then the value you want to be assigned to it. For example:

const MY_CONSTANT_VARIABLE = 5;

Once you have declared a constant variable, you cannot reassign it to a different value. If you try to do so, you will get an error. For example:

const MY_CONSTANT_VARIABLE = 5;
// This will cause an error
MY_CONSTANT_VARIABLE = 10;

Initializing Const Variables

You must initialize a constant variable when you declare it. This means that you must assign it a value in the same declaration. For example:

const MY_CONSTANT_VARIABLE = 5;

If you try to declare a constant variable without initializing it, you will get an error. For example:

// This will cause an error
const MY_CONSTANT_VARIABLE;

Scope of Const Variables

Const variables have the same scope as variables declared with the let keyword. This means that they are block-scoped. This means that their scope is limited to the block of code in which they are declared. For example:

{
const MY_CONSTANT_VARIABLE = 5;

console.log(MY_CONSTANT_VARIABLE); // 5
}

console.log(MY_CONSTANT_VARIABLE); // ReferenceError: MY_CONSTANT_VARIABLE is not defined

When to Use Const Variables

You should use const variables whenever you know that the value of a variable should not be changed. This can help to prevent accidental changes to important variables in your code. For example, you might use const variables to declare the following:

Constants such as mathematical constants (e.g., PI) or physical constants (e.g., SPEED_OF_LIGHT).

Enum values.

Global configuration variables.

Function parameters.

Using Const Variables with Objects and Arrays

You can also use the const keyword to declare constant objects and arrays. However, this does not mean that the contents of the object or array cannot be changed. It simply means that the variable itself cannot be reassigned to a different object or array. For example:

const MY_CONSTANT_OBJECT = {
name: "John Doe",
age: 30
};

MY_CONSTANT_OBJECT.age = 31;

console.log(MY_CONSTANT_OBJECT.age); // 31

Conclusion

The const keyword is a useful way to prevent accidental changes to important variables in your JavaScript code. You should use it whenever you know that the value of a variable should not be changed.