Sub topic 1
Three Ways to Declare a Variable
JavaScript gives you three keywords for creating variables: let, const, and var. They look alike, but they follow different rules. This chapter covers the basic syntax of each one and how initialization works. Later chapters explain the deeper differences: scope, hoisting, and redeclaration.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript syntax: statements, expressions, and operators
- How to write and call functions
- How
ifstatements andforloops work - How to run code in a browser console or with Node.js and read
console.logoutput - Basic use of objects and arrays
Declaration, Initialization, and Assignment
Three separate steps can happen to a variable, and it helps to name each one before looking at the keywords.
- Declaration creates a named binding, which is the link between a name and a storage slot.
- Initialization gives the binding its first value.
- Assignment replaces the current value with a new one later on.
When you write let count = 0;, the declaration and the initialization happen in a single statement.
The Three Keywords at a Glance
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'letdeclares a variable whose value you expect to change.constdeclares a binding that can never be reassigned after it is initialized.varis the original keyword from before ES2015. It still works, but its scoping rules are looser, as later chapters show.
Initializers Are Optional, Except for const
You can declare a variable with let or var without giving it a value. In that case its value is undefined until you assign one.
let status;
var note;
console.log(status, note); // undefined undefined
status = 'ready';
console.log(status); // 'ready'const works differently. Because a const binding can never be assigned later, JavaScript requires the value in the declaration itself. If you leave it out, the code fails to parse before any line runs:
const apiUrl = 'https://example.com/api'; // correct
// const timeout; // SyntaxError: Missing initializer in const declaration
console.log(apiUrl);Declaring Several Variables at Once
All three keywords accept a comma-separated list. Every name in the list gets the same keyword.
let x = 1, y = 2, z;
const width = 100, height = 50;
console.log(x, y, z, width * height); // 1 2 undefined 5000This is legal, but many style guides prefer one declaration per line. Separate lines make diffs easier to read and make it obvious which names have no initial value, like z above.
Common Errors
| Mistake | What happens |
|---|---|
| `const n;` with no value | SyntaxError when the code is parsed |
| `n = 5;` after `const n = 1;` | TypeError when that line runs |
| Using `let` with no initializer, then reading it | You get `undefined`, which can hide bugs |
| Assigning to a name you never declared | Creates an accidental global or throws, depending on strict mode (covered later) |
A useful habit is to start with const. Switch to let only when you find you actually need to reassign the variable. A later chapter explains this guideline in detail, along with the few cases where you might still see var.
Exercise
What does this code print, or does it fail? let a; const b = 2; var c = 'hi'; a = b * 3; console.log(a, b, c);
Show answer
It prints 6 2 'hi'. a starts as undefined and is then assigned 6. b is a correctly initialized const that is never reassigned, and c is a normal var.
Exercise
A teammate writes const total; and plans to set total inside an if statement further down. Why does this fail, and what should they use instead?
Show answer
const must be initialized in its declaration, so const total; is a SyntaxError and the script never runs. They should use let total; and assign it later, or restructure the code so the value can be computed in the const declaration itself, for example with a ternary expression.