var, let and const

  • var:
    • scope:
      • global scoped if defined outside function
      • else function scoped
    • initialized with undefined
    • updation is possible
    • redeclaration is possible
  • let: (introduced in ES6)
    • scope: block scoped
    • Need to initialized before use otherwise Reference error happens
    • updation is possible
    • re-declaration is not possible within scope:
    let x = 3;
    let x = 3; // error
  • const: (introduced in ES6)
    • scope: block scoped
    • updation is not possible
    • Need to initialized before use otherwise Reference error happens
    • re-declaration is not possible within scope
    • Must be initialized during declaration otherwise Syntax Error Happens

Hoisting

  • var is hoisted and value can be accessed before it is declared but it is always undefined
console.log(x) // undefined
var x = 3;
 
console.log(y); // ReferenceError
const y = 3;
 
console.log(z); // ReferenceError
let z = 3;
 
  • let and const are also hoisted but they show that behavior in some certain cases like:
const x = 1;
{
  console.log(x); // ReferenceError
  const x = 2;
}

Variables declared without var, let and const

  • If you declare a variable without var, let or const you will make the variable global irrespective of where it is declared
function foo() {
   gblVar = 3; // declares global variable
   const l = 1;
   let r = 2;
   return l + r;
}
 
foo();
 
console.log(gblVar); // 3
console.log(window.gblVar); // 3 assuming browser js
console.log(l); // Reference error
console.log(r); // Reference error

Shadowing

  • If a same-named variable is declared inside the function then it shadows the outer one.
let userName = 'John';
 
function showMessage() {
  let userName = "Bob"; // declare a local variable
 
  let message = 'Hello, ' + userName; // Bob
  alert(message);
}
showMessage();
alert(userName); // John, unchanged,