Middle+
What are the scopes of let/const and var? Is there another way to declare variables besides var, let, const?
sobes.tech AI
Answer from AI
Variable scope in JavaScript:
-
var — has function scope. If declared outside a function, it becomes a global variable. The variable is accessible throughout the entire function body, regardless of block.
-
let and const — have block scope. Variables are only accessible within the nearest curly braces (e.g., inside if, for, or function block).
Differences:
- var can be redeclared and reassigned within the same scope, while let and const cannot be redeclared; const cannot be reassigned.
Other ways to declare variables:
- Global variables without var/let/const — not recommended, but if a value is assigned to a variable without declaration, it is created in the global scope (will cause an error in strict mode).
- Declaration via function parameters — function parameters are also local variables.
- Declaration via import/export — in ES6 modules, variables can be imported or exported, which also affects scope.
Example:
function example() {
if (true) {
var a = 1; // accessible throughout the function
let b = 2; // only accessible inside if
const c = 3; // also block scope
}
console.log(a); // 1
console.log(b); // ReferenceError
console.log(c); // ReferenceError
}