AI Hints
Home›JavaScript Tutorial›Arrow Functions and Scope
JavaScript · Lesson 35 of 138

Scope

Where variables live.

⏱ 2 min read▶ Video at 42:30🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

A variable made inside a function can't be seen outside it. A variable made inside an if block can't be seen outside the block. Where a variable can be used is called its scope.

Scope
From the video: Scope
  • Inside a function
  • Inside a block
  • Where it can be used: scope

Inside and outside

App name is declared at the top, so it's visible everywhere. Message is declared inside the function, so it only exists in there. And bonus is declared with let inside the if block, so it disappears when the block ends. Run it. Trying to use message outside the function gives a reference error.

app.jsjavascript
const appName = "Notes";

function show() {
  const message = `Welcome to ${appName}`;
  console.log(message);
}
show();

if (true) {
  let bonus = 10;
}

try { console.log(message); }
catch (e) { console.log("Outside:", e.message); }
Output
Welcome to Notes
Outside: message is not defined

Why scope is good

Scope keeps variables private, so different parts of a program don't clash. Two functions can both use a variable called total, without interfering. A good rule is to declare variables in the smallest scope you can, close to where you use them.

keyvalue
Globalvisible everywhere
Function scopeinside the function
Block scopelet and const in { }
Rulesmallest scope possible

Summary

Scope decides where a variable can be used. Let and const are block scoped, and function variables stay inside. Next, closures.

Key takeaways
  • Global vs local
  • let/const are block scoped
  • Keep scopes small
Next up: Closures — functions that remember