var , let ,const in JS

·

1 min read

  • Variables declared with 'var' keyword are function-scoped whereas variables declared with 'let' and 'const' are block-scoped and they exist only in the block in which they are defined.

  • In 2015, JavaScript introduced two new keywords to declare variables: let and const.

function Aaaa(Name="Willson")
{
  if(true)
  {
    let testvar="it let";

  }
   console.log(testvar);
console.log("Say your name!!"+Name);

}

above code will throw a Reference Error that testvar is not defined.

  • the below code will work properly as var is function scoped :
 function Aaaa(Name="Willson")
{
  if(true)
  {
    var testvar="it let";

  }
   console.log(testvar);
console.log("Say your name!!"+Name);

}