JavaScript constants

JavaScript constants are a way to declare variables that cannot be reassigned a new value later on in the code. They are useful for defining values that should never change throughout the lifetime of a program. In this tutorial, we will cover the basics of JavaScript constants and how to use them effectively in your code.

The "const" keyword is used to declare a constant in JavaScript. Once a constant is declared, its value cannot be changed. Attempting to reassign a new value to a constant will result in a TypeError.

1const PI = 3.14; 2PI = 3.142; // TypeError: Assignment to constant variable. 3console.log(PI); // 3.14

It is also important to note that JavaScript constants cannot be reassigned, but the properties of an object or array that are constants can be modified.

1const myObject = {name: "William"}; 2myObject.name = "Mike"; // This is valid 3console.log(myObject); // {name: "Mike"} 4 5myObject = {name: "Max"}; // TypeError: Assignment to constant variable.

When working with constants, it's a good practice to use uppercase letters and underscores to distinguish them from regular variables. This makes it easy to identify constants in your code and also makes it clear that these values should not be reassigned.

1const MAX_USERS = 100;

JavaScript constants can also be used in different ways. When declaring an array, we can use constants to make sure that the values are not changed in the future.

1const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; 2days[0] = "Sunday"; // This is valid 3console.log(days); // ["Sunday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 4 5days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; // TypeError: Assignment to constant variable.

Note: Constants are a great way to make sure that important values in your code are not accidentally modified, and can help to make your code more maintainable and predictable. It is also a good practice to use uppercase letters and underscores when naming constants, and also use them in arrays and objects to make sure that the values are not changed later on.