JavaScript const

Are you ready to learn about the powerful JavaScript const keyword? Const is a way of declaring a variable that cannot be reassigned. It is a great way to ensure that your code is clean and maintainable by making sure that your variables are not changed accidentally. This tutorial will teach you all about the const keyword and how to use it in your JavaScript code.

Why should you use it?

  • It helps ensure that your variables are not changed accidentally.
  • It makes your code more maintainable and easier to debug.
  • It makes your code more secure by preventing malicious code from changing your variables.

Const

The keyword const is a signal that the identifier won’t be reassigned. A constant can be declared with the const keyword. Once a constant is declared, it cannot be reassigned a different value. Constants are block-scoped, much like variables defined using the let keyword.

Example 1:

script.js
const PI = 3.14;
console.log(PI);
In the example above, a constant named PI is declared as a part of the global scope. It is initialized with a value of 3.14. If you try to reassign the constant, a TypeError will be thrown.

Example 2:

script.js
const MAX_SIZE = 10;
for (let i = 0; i < MAX_SIZE; i++) {
  console.log(i);
}
In this example, a constant named MAX_SIZE is declared and initialized with a value of 10. The constant is then used in a for loop to limit the number of iterations.

Example 3:

script.js
const MAX_SIZE = 10;
MAX_SIZE = 20; // TypeError: Assignment to constant variable
In this example, a constant named MAX_SIZE is declared and initialized with a value of 10. The constant is then used in a for loop to limit the number of iterations.

Example 4:

script.js
const MAX_SIZE = 10;
for (let i = 0; i < MAX_SIZE; i++) {
  console.log(i);
}
In this example, a constant named MAX_SIZE is declared and initialized with a value of 10. The constant is then used in a for loop to limit the number of iterations. The loop is also using the let keyword to declare a variable named i, which is scoped to the loop.