Global Scope: Variables declared outside of any function or block are in the global scope. They can be accessed from anywhere in the code.
javascriptvar globalVar = "I am global"; function checkGlobal() { console.log(globalVar); // "I am global" } checkGlobal(); console.log(globalVar); // "I am global"
Function Scope: Variables declared inside a function are scoped to that function and are not accessible outside it.
javascriptfunction myFunction() { var functionVar = "I am function scoped"; console.log(functionVar); // "I am function scoped" } myFunction(); console.log(functionVar); // ReferenceError: functionVar is not defined
Block Scope: Introduced with
let
andconst
in ES6, variables declared within a block (enclosed by{}
) are scoped to that block.javascrifunction blockScopeExample() { if (true) { let blockVar = "I am block scoped"; console.log(blockVar); // "I am block scoped" } console.log(blockVar); // ReferenceError: blockVar is not defined } blockScopeExample();
Lexical Scope: This is the scope created by the position of variables and functions in the source code. Inner functions have access to the variables in their outer functions due to lexical scoping.
javascriptfunction outerFunction() { var outerVar = "I am outside"; function innerFunction() { console.log(outerVar); // "I am outside" } innerFunction(); } outerFunction();
Each type of scope plays a role in determining the accessibility of variables and functions, affecting how code is structured and executed.
No comments:
Post a Comment