Definition on global scope and local scope

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5175

    #1

    Definition on global scope and local scope

    In JavaScript, scope refers to the visibility or accessibility of variables. There are two main types of scope:


    Global Scope:
    • Variables declared outside of any function or block are in the global scope.
    • They can be accessed from anywhere in the code.
    • It's generally considered bad practice to use too many global variables, as they can make your code harder to maintain and debug.


    Local Scope:
    • Variables declared inside a function or block are in the local scope.
    • They can only be accessed within that function or block.
    • Local variables are created when a function is called and destroyed when the function returns.


    Here's an example:






    // Global variable
    let globalVar = "I'm a global variable";

    function myFunction() {
    // Local variable
    let localVar = "I'm a local variable";

    console.log(localVar); // Output: "I'm a local variable"
    console.log(globalVar); // Output: "I'm a global variable"
    }

    myFunction();
    console.log(localVar); // Error: localVar is not defined
    console.log(globalVar); // Output: "I'm a global variable"







    In this example, globalVar is a global variable, so it can be accessed both inside and outside of myFunction. localVar is a local variable, so it can only be accessed inside myFunction.


    Understanding scope is important for writing clean and maintainable code. By using local variables when possible, you can avoid naming conflicts and make your code easier to understand.




    More...
Working...