0 votes
in JavaScript by
What is the difference between let and var in Javascripts?

1 Answer

0 votes
by

You can list out the differences in a tabular format

varlet
It is been available from the beginning of JavaScriptIntroduced as part of ES6
It has function scopeIt has block scope
Variables will be hoistedHoisted but not initialized

Let's take an example to see the difference,

function userDetails(username) {
  if (username) {
    console.log(salary); // undefined due to hoisting
    console.log(age); // ReferenceError: Cannot access 'age' before initialization
    let age = 30;
    var salary = 10000;
  }
  console.log(salary); //10000 (accessible due to function scope)
  console.log(age); //error: age is not defined(due to block scope)
}
userDetails("John");
...