Functional Scopes
Topic 3JavaScript Part 1
Functional Scopes
Introduction
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 and Definitions
Function Scope
Variables declared inside a function are not accessible outside of it.
Example:
function greet() {
var message = 'Hello!';
console.log(message);
}
console.log(message); // ReferenceErrorStep-by-Step Explanation
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();
}Practice Exercises
- •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.
Interview guide discussion
(0)Join the discussion — login to comment and help other developers.
Login to comment