By the end of this lesson, learners will be able to:
var
, let
, and const
in terms of scopeScope defines where in your code a variable can be accessed or used.
In JavaScript, variables can be:
Think of scope like a “visibility zone” for a variable.
A variable declared outside of any function is in the global scope. You can use it anywhere in your code.
let siteName = "Codevisionz";
function showSite() {
console.log(siteName); // ✅ Accessible
}
showSite();
console.log(siteName); // ✅ Also accessible
✅ Global variables are accessible inside functions
❌ But global variables can be accidentally changed or overwritten
var
)A variable declared inside a function using var
is only available within that function.
function greet() {
var message = "Hello!";
console.log(message); // ✅ Accessible
}
greet();
console.log(message); // ❌ Error: message is not defined
🧠 This is called function scope — message
lives and dies inside the function.
let
and const
)Variables declared with let
or const
are block-scoped. They exist only within the nearest { }
block, such as:
if (true) {
let mood = "happy";
const weather = "sunny";
console.log(mood, weather); // ✅ Accessible inside block
}
console.log(mood); // ❌ Error: mood is not defined
console.log(weather); // ❌ Error: weather is not defined
✅ let
and const
respect block-level boundaries
❌ var
does not — which can lead to bugs
var
vs. let
/const
Feature | var | let / const |
---|---|---|
Scope type | Function scope | Block scope |
Redeclaration | ✅ Allowed | ❌ Not allowed with let/const |
Hoisting | ✅ Hoisted but undefined | ❌ Hoisted but not initialized |
Modern usage | ❌ Avoid if possible | ✅ Use let or const |
A variable exists as long as its scope allows:
{}
let user = "Lisa";
function greetUser() {
let greeting = "Hello";
console.log(greeting + ", " + user); // Hello, Lisa
}
greetUser();
console.log(greeting); // ❌ Error: greeting is not defined
🧠 user
is global, so it’s accessible
🧠 greeting
is local to the function
You can declare a local variable with the same name as a global one. The local one will “shadow” the global one.
let message = "Hi (global)";
function showMessage() {
let message = "Hi (local)";
console.log(message); // Output: Hi (local)
}
showMessage();
console.log(message); // Output: Hi (global)
Scope Type | Declared With | Accessible Where | Lifetime |
---|---|---|---|
Global | Outside functions | Everywhere | Entire script/app |
Function Scope | var | Inside the function only | During function execution |
Block Scope | let , const | Inside { } blocks only | While inside the block |