In JavaScript, the terms var and let are both used to declare variables, but var is function scoped whereas let is block scoped. As opposed to let, a variable declared with var is said to be defined throughout the entire program.
You can list out the differences in a tabular format
var | let |
---|---|
It has been accessible since since JavaScript first debuted | is a component of ES6 |
There is a function scope | There is a block scope. |
Variables will be hoisted | Hoisted but not initialized |
Let’s use a comparison to highlight the differences.
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 to due function scope)
console.log(age); //error: age is not defined(due to block scope)
}
userDetails("John");
Note: In the case of global scope, var and let will both function equally. For instance,
var a = 5; / 5
A will have a worldwide reach and be accessible throughout the rest of the program.let a = 5; / 5
A will have a worldwide reach and be accessible throughout the rest of the program.