Difference Between Let Var and Const in JavaScript

Var

  • Variables declared with var are function-scoped, meaning their scope is limited to the function in which they are declared.
  • If a variable is declared with var outside of any function, it becomes a global variable.
  • var declarations are hoisted to the top of their scope, so you can use the variable before it's declared in the code.
  • You can again declare the variable with same name in var.
  • It can be accessed without initialization as its default value is “undefined”.
var x= 10; // Global Scope
function myFunction(){
    var x = 20; // Function Scope
    console.log(x)
}
myFunction();
 console.log(x) // Return 10 and 20
  • if you call the variable before they declare they give the undefined error. The reason is that due to the function scoped.
console.log(x) // Return Undefined Because its call before
var x= 10; // Global Scope

Let

  • Let has Block scope.
  • They cann't access outside the block.
  • If you call the let variable before declared variable they give reference error.
  • Once the variable name is declare with let you can't declare it again.
  • You can update the value of the variable.
  • It cannot be accessed without initialization otherwise it will give ‘referenceError’.
let a = 10;
function f() {
    if (true) {
        let b = 9
        // It prints 9
        console.log(b);
    }
    // It gives error as it b/c it is defined in if block
    console.log(b);
}
f()
// It prints 10
console.log(a)

Const

  • Working same as let except you can't update the value of the variable. It cannot be accessed without initialization, as it cannot be declared without initialization.
const name = "Hassan Ali"