In JavaScript, local scope refers to the scope that is accessible only within a specific function or block. Variables declared within this scope are not accessible outside the function or block in which they are defined. Understanding local scope is crucial for managing variable visibility and avoiding naming conflicts in your code.
Types of Local Scope
1. Function Scope
2. Block Scope
1. Function Scope
In JavaScript, variables declared with var, let, or const inside a function are considered to have function scope. This means they can only be accessed within that function.
functionScope.js
function exampleFunction() { var functionScopedVar = "I'm a function-scoped variable!"; console.log(functionScopedVar); // This will work. } exampleFunction(); try{ console.log(functionScopedVar); // This will throw an error: Uncaught ReferenceError: functionScopedVar is not defined }catch(e){ console.log('Error occurred while accessing functionScopedVar outside of the function.\n\tError: ' + e.message) }
Output
I'm a function-scoped variable! Error occurred while accessing functionScopedVar outside of the function. Error: functionScopedVar is not defined
2. Block Scope
Block scope is introduced with the let and const keywords. Variables declared with let or const inside a block (i.e., between a pair of curly braces {}) are not accessible outside that block.
blockScope.js
if (true) { let blockScopedVar = "I'm a block-scoped variable!"; console.log(blockScopedVar); } try{ console.log(blockScopedVar); // This will throw an error: Uncaught ReferenceError: blockScopedVar is not defined } catch(e){ console.log('Error occurred while accessing functionScopedVar outside of the function.\n\tError: ' + e.message) }
Output
I'm a block-scoped variable! Error occurred while accessing functionScopedVar outside of the function. Error: blockScopedVar is not defined
Differences Between Function Scope and Block Scope
var vs let/const
1. var is function-scoped, meaning it only cares about the function. It doesn’t respect blocks like loops or conditionals.
2. let and const are block-scoped, meaning they respect both function and block scopes.
functionVsBlockScope.js
function scopeExample() { if (true) { var functionScopedVar = "I'm function-scoped!"; let blockScopedVar = "I'm block-scoped!"; const blockScopedConst = "I'm also block-scoped!"; } console.log(functionScopedVar); try{ console.log(blockScopedVar); }catch(e){ console.log('Error occurred while accessing blockScopedVar\n\tError: ' + e.message) } try{ console.log(blockScopedConst); }catch(e){ console.log('Error occurred while accessing blockScopedConst\n\tError: ' + e.message) } } scopeExample();
Output
I'm function-scoped! Error occurred while accessing blockScopedVar. Error: blockScopedVar is not defined Error occurred while accessing blockScopedConst. Error: blockScopedConst is not defined
No comments:
Post a Comment