Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Scope is like rooms in a house. A variable created in one room might not be visible in another room. Scope determines where you can use your variables!
Variables declared outside functions are global - they can be used anywhere in your entire program
// Global variable (outside everything)
const userName = 'Alice';
function greet() {
console.log('Hello, ' + userName);
}
function sayGoodbye() {
console.log('Bye, ' + userName);
}
greet(); // Can use userName
sayGoodbye(); // Can use userName
console.log(userName); // Can use it here tooVariables declared at the top level are accessible everywhere
Variables declared inside functions are local - they only exist within that function
function greet() {
// Local variable (inside function)
const message = 'Hello!';
console.log(message); // Works!
}
greet(); // Hello!
// Try to use message outside function
console.log(message); // ❌ ERROR!
// message is not definedVariables declared inside functions stay inside
With let and const, variables inside curly braces { } stay inside those braces
if (true) {
const greeting = 'Hello!';
console.log(greeting); // Works!
}
// Outside the block
console.log(greeting); // ❌ ERROR!
// greeting only exists inside the if blocklet and const are block-scoped
If JavaScript can't find a variable in the current scope, it looks in the outer scope, then the next outer scope, and so on...
const country = 'USA';const city = 'Boston';const name = 'Alice';Can access: name, city, country
Inner functions can access outer variables
Variables outside functions work anywhere
Variables inside functions stay inside
let/const inside { } stay in that block
Inner scopes can see outer variables