DEV Community

API crud
API crud

Posted on

Basic Javascript Knowledge: When to use var, let or const?

In JavaScript, variables are essential for storing data. The keywords var, let, and const provide different ways to declare these variables.

var

  • Scope: Function scope.
  • Hoisting: Variables are hoisted.
  • Re-assignment: Allowed.
  • Re-declaration: Allowed.
  function testVar() {
    var x = 1;
    if (true) {
        var x = 2; // same variable!
        console.log(x); // 2
    }
    console.log(x); // 2
  }
  testVar();
Enter fullscreen mode Exit fullscreen mode

let

  • Scope: Block scope.
  • Hoisting: Hoisted but not initialized.
  • Re-assignment: Allowed.
  • Re-declaration: Not allowed.
  function testLet() {
    let y = 1;
    console.log(y); // 1
    if (true) {
        let y = 2; // different variable
        console.log(y); // 2
    }
    y = 5
    console.log(y); // 5
  }
  testLet();
Enter fullscreen mode Exit fullscreen mode

const

  • Scope: Block scope.
  • Hoisting: Hoisted but not initialized.
  • Re-assignment: Not allowed.
  • Re-declaration: Not allowed.
  • Initialization: Required during declaration.
  function testConst() {
    const z = 1;
    // z = 2; // Error: Uncomment this see error
    console.log(z);
  }
  testConst();
Enter fullscreen mode Exit fullscreen mode

Exercise: Try This To Practise Using Variables

  1. Var Scope: Use var in a loop, then access it outside.
  2. Let Block Scope: Try let in a loop and access it outside the block.
  3. Const Immutability: Attempt re-assigning a const variable.

Good luck!

Top comments (0)