In JavaScript, let
and var
are both used to declare variables, but they have some important differences in terms of scope and behavior.
- The
var
keyword was used to declare variables before the introduction oflet
andconst
in ECMAScript 6 (ES6). Variables declared withvar
are function-scoped, which means they are only accessible within the function in which they were declared, or if they were declared outside any function, they are accessible throughout the global scope. If a variable is declared withvar
keyword inside a function, it is still accessible throughout the function, even if it’s declared inside an if-statement or for loop, for example.
function varFunction() {
if (true) {
var x = 5;
}
console.log(x); // Output: 5
}
varFunction();
console.log(x); // Output: 5
- The
let
keyword was introduced in ECMAScript 6 (ES6) as an alternative tovar
, and it is block-scoped. Variables declared withlet
are only accessible within the block in which they were declared.
function letFunction() {
if (true) {
let x = 5;
}
console.log(x); // ReferenceError: x is not defined
}
letFunction();