JAVASCRIPT Tutorial

const in JS

'const' is a keyword introduced in ES6 that enables the declaration of constant variables. These variables have the following characteristics:

  1. Block Scope:
  • 'const' variables are block-scoped, meaning they are only accessible within the block (e.g., curly braces) in which they are declared. They cannot be accessed outside that block.
  1. No Re-declaration:
  • Once a 'const' variable is declared, it cannot be re-declared within the same scope. Re-declaring a 'const' variable will result in an error.
  1. No Re-assignment:
  • The value of a 'const' variable cannot be re-assigned after initialization. Attempting to do so will result in an error.

Example:

// Declare a constant variable named PI
const PI = 3.14159;

// Attempt to re-declare PI (will result in error)
const PI = 2.718;

// Attempt to re-assign the value of PI (will result in error)
PI = 1.618;

By using 'const', you ensure that critical values remain unchanged throughout your code, preventing unforeseen errors.