Scope basics
Learn why variables declared inside a function are not accessible from outside.
Function scope
Variables declared with let or const inside a function only live inside that function. This is called function scope. They cannot be reached from outside.
For example: function calc() { let total = 10; return total; }. Here total lives only inside calc. If you write total outside the function, you get an error. This prevents name clashes and keeps code safe.
Local and outer variables
If a variable is declared outside a function, the function can still reach it. This is the outer scope. But if you declare a variable with the same name inside the function, the inner one hides the outer; this is called shadowing.
Example: let name = "Alex"; function greet() { let name = "Sam"; console.log(name); }. Calling greet() prints Sam because the inner name shadows the outer one. The outer name stays unchanged.
Exercise Use a local variable
Define a function called makeGreeting. Inside it, declare a local variable with let message and assign it a welcome text. Then return message. Finally print the result with console.log(makeGreeting()).
Show example solution
function makeGreeting() {
let message = "Welcome";
return message;
}
console.log(makeGreeting());
Test yourself
-
Can you reach total from outside the function?
function calc() { let total = 10; return total; } console.log(total);- Yes, it prints 10
- No, it throws ReferenceError
- Yes, it prints undefined
- No, it is silently skipped
Show answer
No, it throws ReferenceError — Correct. total is in function scope, not reachable from outside.
-
Declare a local variable
function showName() { ____ name = "Alex"; console.log(name); } showName();Show answer
function showName() { let name = "Alex"; console.log(name); } showName(); -
Match each variable to its scope
- let inside a function
- Local scope
- let outside a function
- Outer scope
- inner hides outer
- Shadowing
- access inner from outside
- ReferenceError