
Essentially, the keywords let and var serve the same purpose as each other in JavaScript, but they are used in different contexts. When used outside of a function block, the var and let keywords are actually exactly the same. It’s when they are used within a function that they differ from each other. The var keyword declares a variable for an entire function, meaning it’s available for use and visible throughout the entire function. Let is only scoped to the nearest function block, rather than the whole function. This means that when you declare a variable using let within a function, it’s only available within the block (the function block is typically defined by the curly braces: {}) that it has been declared within.
function letVsVar() {
//pizza is not available up here
for( let pizza = 0; pizza < 3; pizza++ ) {
//pizza is only available within this function (inside of the () and {})
}
//pizza is not available down here
}
The above examples show exactly where the let variable can be accessed within the function. Below, we’ve replaced let with var, so you can see how it is visible and available throughout the scope of the entire function, not just within the block.
function letVsVar() {
//pizza works up here
for( var pizza = 0; pizza < 3; pizza++ ) {
//pizza is available here, there, and everywhere within this function
}
Console.log(pizza)
// because pizza is available down here as well
}