In JavaScript, the const keyword is used to declare a constant variable, which means the variable cannot be reassigned after it has been initialized. Here are some key points about using const in JavaScript:

  1. Declaration and Initialization:

    javascript
    const myConstant = 42;

    When you use const, you must initialize the variable at the time of declaration.

  2. Reassignment is Not Allowed:

    javascript
    const myConstant = 42; // This will result in an error myConstant = 20;

    Once a variable is declared using const, you cannot reassign it.

  3. Block Scope: Like let, const is block-scoped. It means it is only accessible within the block or statement on which it is defined.

    javascript
    if (true) { const blockScoped = "I am inside the block"; } // This will result in an error console.log(blockScoped);
  4. Object and Array Constants: While const prevents the reassignment of the variable itself, it doesn't make the values within an object or array immutable.

    javascript
    const myArray = [1, 2, 3]; myArray.push(4); // This is allowed const myObject = { key: "value" }; myObject.key = "new value"; // This is allowed

    If you want to make the values within an object or array immutable, you would need to use other techniques like Object.freeze() or libraries like Immutable.js.

  5. Use in Loops: const can be useful in loops to declare loop variables that should not be reassigned.

    javascript
    for (const i = 0; i < 5; i++) { // This will result in an error because i cannot be reassigned }
  6. Constants in Uppercase: It is a common convention to use uppercase letters for constant variables.

    javascript
    const MY_CONSTANT = 100;

    This makes it easier to identify constants in your code.

Remember that const doesn't make the variable or its contents truly immutable, it just prevents the variable from being reassigned. If you want to achieve immutability at a deeper level, you would need to use other techniques or libraries.