What is the difference between 'var', 'let', and 'const' in JavaScript?

QuestionsQuestions8 SkillsProBasic JavaScript and DOMSep, 14 2025
0166

In JavaScript, var, let, and const are used to declare variables, but they have different scopes and behaviors:

  1. var:

    • Scope: Function-scoped. If declared outside a function, it is globally scoped.
    • Hoisting: Variables declared with var are hoisted to the top of their scope, meaning they can be accessed before their declaration (but will be undefined until the declaration is reached).
    • Re-declaration: You can re-declare a variable using var within the same scope.
    var x = 10;
    console.log(x); // 10
  2. let:

    • Scope: Block-scoped. It is only accessible within the block (e.g., within {}) where it is defined.
    • Hoisting: Variables declared with let are also hoisted, but they cannot be accessed before their declaration (this is known as the "temporal dead zone").
    • Re-declaration: You cannot re-declare a variable using let in the same scope.
    let y = 20;
    if (true) {
      let y = 30; // Different scope
      console.log(y); // 30
    }
    console.log(y); // 20
  3. const:

    • Scope: Block-scoped, similar to let.
    • Hoisting: Like let, const variables are hoisted but cannot be accessed before their declaration.
    • Re-declaration: You cannot re-declare a variable using const in the same scope.
    • Immutability: Variables declared with const must be initialized at the time of declaration and cannot be reassigned. However, if the variable is an object or array, its properties or elements can still be modified.
    const z = 40;
    // z = 50; // This will throw an error
    const obj = { key: 'value' };
    obj.key = 'newValue'; // This is allowed

Summary:

  • Use var for function-scoped variables (less common in modern JavaScript).
  • Use let for block-scoped variables that may change.
  • Use const for block-scoped variables that should not be reassigned.

If you have any further questions, feel free to ask!

0 Comments

no data
Be the first to share your comment!