Skip to main content
πŸ“œ WAYPOINT LESSON

Scope and Arrow Functions

⭐ beginner⏳ 14 min readπŸ“ Lesson 33 of 143

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 with return

Next: arrays β€” working with lists of data.

⚑ Now practice

Ready to Code
Scope and Arrow Functions β€” PracticeHands-on practice for β€œScope and Arrow Functions”: apply what you just learned in js-scope-and-arrows.
1 challenge Β· Β· ~10 min