About Lesson
Scope of Variables:
Scope determines the visibility or accessibility of variables in different parts of your code.
1. Global Scope:
Variables declared outside any function or block have global scope, meaning they can be accessed anywhere in the program.
Example:
JavaScript
var globalVar = "I'm global!";
function display() {
console.log(globalVar); // Accessible here
}
display();
2. Local/Function Scope:
Variables declared inside a function are local to that function and can’t be accessed from outside.
Example:
JavaScript
function display() {
var localVar = "I'm local!";
}
console.log(localVar); // Error: localVar is not defined
3. Block Scope:
Variables declared with let or const within a block ({}) are limited to that block.
Example:
JavaScript
if (true) {
let blockVar = "I'm block-scoped!";
}
console.log(blockVar); // Error: blockVar is not defined