Functional Scopes
Functional scope is the area in code where a variable is accessible. In JavaScript, variables declared with var are function-scoped, limiting their access to the containing function.
Key concepts
Function Scope
Variables declared inside a function are not accessible outside of it.
Examplefunction greet() {
var message = 'Hello!';
console.log(message);
}
console.log(message); // ReferenceErrorStep by step
Variable Access:
- Only accessible within the same function.
Nested Functions:
Inner functions can access variables from their parent scope.
function outer() {
var outerVar = 'Outer';
function inner() {
console.log(outerVar);
}
inner();
}Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Write a function and declare variables within it. Test their accessibility outside the function.
- Nest functions and observe variable scope.
Summary
Function scope ensures variables are encapsulated within functions, preventing unintended access.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus