In JavaScript, the scope of a variable defines the regions of code where it can be accessed. Scope can be either global or local.
-
Global Scope: When declared outside a function, a variable has global scope, meaning it can be accessed and modified anywhere in the code. Global variables remain accessible throughout the entire lifetime of the web page.
Example:
javascriptvar globalVar = "This is a global variable"; function demoFunction() { console.log(globalVar); // Accessing global variable } demoFunction(); // Output: This is a global variableThe
globalVarabove is a global variable that can be accessed within thedemoFunctionfunction. -
Local Scope: When a variable is declared inside a function, it has local scope, meaning it can only be accessed and modified within that function. Local variables are inaccessible to code outside the function.
Example:
javascriptfunction demoFunction() { var localVar = "This is a local variable"; console.log(localVar); // Accessing local variable } demoFunction(); // Output: This is a local variable // console.log(localVar); // Error: localVar is not accessible herelocalVarcan only be accessed within thedemoFunctionfunction. -
Block Scope: Variables declared with
letandconsthave block scope. They are accessible only within the code block where they are declared, such as inside a for loop or an if statement.Example:
javascriptif (true) { let blockScopedVar = "This is a block-scoped variable"; console.log(blockScopedVar); // Accessing block-scoped variable } // console.log(blockScopedVar); // Error: blockScopedVar is not accessible here
In practical application development, it is advisable to use local or block scope for variable declarations to prevent naming conflicts and bugs that are difficult to trace, which can be caused by global variables.