Scope and Arrow Functions
Where variables live and who can see them — plus the shorter arrow syntax you will meet in every modern codebase.
Scope: where a variable is visible
Variables declared inside a function exist only inside it:
function calc() {
const result = 42; // born inside, dies inside
return result;
}
console.log(result); // ReferenceError — result is not visible out here
But the reverse works: a function can read variables declared outside it:
const rate = 0.2; // outer scope
function tax(amount) {
return amount * rate; // reads the outer variable
}
This is scope: inner sees outer, outer never sees inner. Keep most variables as local as possible — a variable only one function needs belongs inside that function.
Arrow functions — the shorter syntax
const double = function (n) {
return n * 2;
};
const doubleArrow = (n) => n * 2; // identical behavior
An arrow function is an expression assigned to a variable. With one expression
after =>, the value is returned automatically and the braces disappear.
With a block body, write return yourself:
const shout = (text) => text.toUpperCase() + "!"; // implicit return
const compare = (a, b) => {
if (a === b) return 0;
return a > b ? 1 : -1;
}; // block body → explicit return
You will see both constantly. function declarations are still perfect —
use whichever reads better; recognize both.
Arrows in loops-over-data (a preview)
const scores = [90, 72, 88];
scores.map((s) => s * 2); // arrows are the natural fit here — arrays lesson next
What you learned
- Inner scope sees outer variables; outer never sees inner
- Keep variables as local as possible
- Arrow:
(params) => expression(implicit return) or a block withreturn
Next: arrays — working with lists of data.