Diferance between var, let , const in javascript

 In JavaScript, var, let, and const are used to declare variables, but they differ in scope, hoisting, and mutability.

Here's a breakdown:

1. var

  • Scope:
    • Function-scoped: A var variable is available within the function it is defined in.
    • It ignores block scope (e.g., if or for blocks).

  • Hoisting:
    • Variables declared with var are hoisted to the top of their scope but are initialized with undefined. This means you can access the variable before its declaration, but its value will be undefined.

    • console.log(x); // undefined
      var x = 5;
Redeclaration:
  • Allowed within the same scope.
  • Example:

    var a = 10;
    var a = 20; // No error Use: Considered outdated and rarely used in modern code.
2. let
  • Scope:
    • Block-scoped: A let variable is only available within the block it is defined in (e.g., inside {}).
  • Hoisting:
    • Variables declared with let are hoisted but are not initialized. Accessing them before declaration results in a ReferenceError due to the "temporal dead zone."

      console.log(y); // ReferenceError
      let y = 10;
  • Redeclaration:
    • Not allowed within the same scope.

      let b = 10;
      let b = 20; // SyntaxError: Identifier 'b' has already been declared
  • Use: Preferred for variables that will be reassigned.

3.const

  • Scope:
    • Block-scoped, like let.

  • Hoisting:
    • Same as let, with a temporal dead zone.

      console.log(z); // ReferenceError
      const z = 15;
  • Redeclaration:
    • Not allowed.

  • Reassignment:
    • Variables declared with const cannot be reassigned.

      const c = 30;
      c = 40; // TypeError: Assignment to constant variable.

  • Mutability:
    • If the variable is an object or an array, you can modify its properties or elements (mutate), but you cannot reassign the entire object or array.

      const obj = { name: "Alice" };
      obj.name = "Bob"; // Allowed
      obj = { name: "Charlie" }; // TypeError
    • Use: Best for values that should not be reassigned, such as constants or configuration values.

Summary Table

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
HoistingHoisted (initialized to undefined)Hoisted (not initialized)Hoisted (not initialized)
RedeclarationAllowedNot allowedNot allowed
ReassignmentAllowedAllowedNot allowed
Use CasesLegacy codeReassignable variablesConstants and immutable references

In modern JavaScript, it's recommended to use let and const instead of var. Use const by default, and switch to let only when reassignment is necessary.