In JavaScript, var and let are used to declare variables, but they have some key differences in terms of scope and hoisting.
var: Variables declared withvarare function-scoped. This means that they are only visible within the function in which they are declared. If a variable is declared outside of any function, it becomes a global variable.let: Variables declared withletare block-scoped. This means that they are only visible within the block (enclosed by curly braces) in which they are defined. This includes if statements, loops, and other block structures.
// Example with var
function exampleVar() {
if (true) {
var x = 10;
}
console.log(x); // Outputs 10, even though x was declared inside the if block
}
// Example with let
function exampleLet() {
if (true) {
let y = 20;
}
console.log(y); // ReferenceError: y is not defined
}
In the exampleVar function, x is accessible outside the if block due to var being function-scoped and hoisted. In the exampleLet function, trying to access y outside the if block results in a ReferenceError because let is block-scoped, and y is not accessible outside the block.
Difference between var and let in JavaScript