In JavaScript, var and const (along with let) are used to declare variables, but they have important differences regarding scope, hoisting, and mutability.

// var example
function exampleVar() {
    if (true) {
        var x = 10;
    }
    console.log(x); // 10, since var is function-scoped
}

// let example
function exampleLet() {
    if (true) {
        let y = 20;
        console.log(y); // 20
    }
    // console.log(y); // ReferenceError, since let is block-scoped
}

// const example
function exampleConst() {
    const z = 30;
    // z = 40; // TypeError, since const cannot be reassigned
    const obj = { key: 'value' };
    obj.key = 'newValue'; // This is allowed
    console.log(obj.key); // 'newValue'
}

exampleVar();
exampleLet();
exampleConst();

var

  • Scope:
  • Function-scoped: Variables declared with var are scoped to the function in which they are declared.
  • They are not block-scoped: If var is declared in a block (e.g., inside an if statement), it is still accessible outside the block.
  1. Hoisting:
  • Variables declared with var are hoisted to the top of their scope. However, the initialization is not hoisted, only the declaration.
  1. Re-declaration:
  • var allows re-declaration within the same scope.

let

  1. Scope:
  • Block-scoped: Variables declared with let are only accessible within the block they are declared in.
  1. Hoisting:
  • Variables declared with let are hoisted but are not initialized. They remain in a “temporal dead zone” until the declaration is encountered.
  1. Re-declaration:
  • let does not allow re-declaration within the same scope.

const

  1. Scope:
  • Block-scoped: Variables declared with const are only accessible within the block they are declared in.
  1. Hoisting:
  • Variables declared with const are hoisted but are not initialized. They remain in a “temporal dead zone” until the declaration is encountered.
  1. Re-declaration:
  • const does not allow re-declaration within the same scope.
  1. Mutability:
  • const creates a read-only reference to a value. However, if the variable is an object or array, the properties or elements can still be modified.

Examples

In summary:

  • Use var for function-scoped variables (although its use is generally discouraged in modern JavaScript).
  • Use let for block-scoped variables that you might need to reassign.
  • Use const for block-scoped variables that should not be reassigned.

Share.

Terry White is a professional technical writer, WordPress developer, Web Designer, Software Engineer, and Blogger. He strives for pixel-perfect design, clean robust code, and a user-friendly interface. If you have a project in mind and like his work, feel free to contact him

Leave A Reply