💻ES6 tutorial: const in javascript

💻ES6 tutorial: const in javascript

·

2 min read

In JavaScript, the const keyword is used to declare a constant, which is a variable that cannot be re-assigned after it is initialized. Constants are block-scoped, meaning they are only accessible within the block where they are defined.

  1. Declaration and Initialization: Constants are declared using the const keyword, followed by the variable name and an optional initializer (value assignment). Once a constant is declared and assigned a value, its value cannot be changed.
const x = 10;
const x = 10;

// Identifier 'x' has already been declared
  1. Block Scoping: Constants are block-scoped, just like variables declared with let and var. This means that they are only accessible within the block in which they are defined.
if (true) {
  const message = "Hello!";
  console.log(message); // Output: Hello!
}

console.log(message); // Error: message is not defined
  1. Immutable Value: The value assigned to a constant cannot be changed or re-assigned. However, for complex data types like objects and arrays, the properties or elements of the object or array can still be modified.
const pi = 3.14;
pi = 3.14159; // Error: Assignment to constant variable.

const person = { name: "John", age: 30 };
person.name = "Jane"; // Valid: Modifying the property of the object.
person = { name: "Jane", age: 25 }; // Error: Assignment to constant variable.
  1. Hoisting: Like variables declared with var, constants declared with const are also hoisted to the top of their scope. Using a const variable before it is declared will result in a ReferenceError
console.log(pi); // Output: ReferenceError: Cannot access 'pi' before initialization

const pi = 3.14;
console.log(pi); // Output: 3.14
  1. Block-Level Re-declaration: Constants cannot be re-declared within the same block scope. Attempting to re-declare a constant within the same block will result in an error.
if (true) {
  const x = 10;
  const x = 20; // Error: Identifier 'x' has already been declared
}

The const keyword is commonly used for values that are not intended to be changed, such as mathematical constants or configuration settings. It helps ensure the immutability of important values in your code, improving code readability and reducing bugs caused by accidental re-assignment.

Â