Sub topic 1
Three Ways to Declare a Variable
Prerequisites
This chapter assumes you know basic JavaScript syntax, can write and call functions, and can use if statements, for loops, and console.log in a browser or Node.js console.
The Three Keywords
JavaScript has three keywords for declaring a variable:
letdeclares a variable you can reassign later.constdeclares a variable that must be initialized when you declare it and cannot be reassigned.varis the older keyword. It works differently from the other two, mainly in where the variable can be seen.
let count = 0; // can be reassigned later
const limit = 10; // must be initialized; cannot be reassigned
var legacy = 'old'; // older function-scoped declaration
count = count + 1;
console.log(count, limit, legacy); // 1 10 'old'Understanding Scope
Scope is the region of code where a variable can be accessed. JavaScript has three kinds you need to know here:
| Scope | Created by | Who uses it |
|---|---|---|
| Global | The top level of a script | All three keywords |
| Function | Each function body | `var` (and `let`/`const` at function level) |
| Block | Any `{ }`, such as `if` or `for` bodies | `let` and `const` only |
When code looks up a name, JavaScript starts in the innermost scope and moves outward until it finds the name.
var and Function Scope
A var declaration belongs to the nearest enclosing function, so blocks do not contain it. A var declared inside an if is still visible anywhere in the function.
let, const, and Block Scope
let and const belong to the nearest enclosing block. Outside that block, the name does not exist.
function demo() {
if (true) {
var a = 1;
let b = 2;
const c = 3;
}
console.log(a); // 1 (var is scoped to the function)
console.log(typeof b); // 'undefined' (b only exists inside the block)
console.log(typeof c); // 'undefined'
}
demo();Exercise
Inside a function, you write for (let i = 0; i < 2; i++) {} and then console.log(i) after the loop. What happens, and what changes if you use var instead?
Show answer
With let, i exists only in the loop's block, so console.log(i) throws a ReferenceError. With var, i is function-scoped and still exists after the loop, so it logs 2.