DEV Community

Sosanya Esther
Sosanya Esther

Posted on

Scopes in JavaScript

What is Scope?
Scope in JavaScript refers to the context or environment in which variables are declared and can be accessed.A solid scope is indispensable because it can affect how your code behaves and interacts with other parts of your application.
JavaScript has two types of scope:
1.Local scope
2.Global scope
These scopes control the accessibility of variables in different parts of your code and play a pivotal role in maintaining code organization and preventing variable conflicts.

  1. Local scope: Any variable that you declare inside a function is said to have Local Scope. Local variables have Function scope: They can only be accessed from within the
    function.Local variables are created when a function starts, and deleted when the function
    is completed. If you try to access any variable defined inside a function from outside or another function, it throws an error.Since you cannot access a local variable from outside the function, you can have a variable of the same name in another function as well.

  2. Global scope: Any variable declared outside of a function is said to have Global Scope.
    In simple terms, a variable that can be accessed anywhere in the program is known as a variable with global scope.
    A global variable has global scope: All scripts and functions on a web page can
    access it.
    Global variables are created when you assign a value to them. Global variables are deleted when you close the page.
    Globally scoped variables can be defined using any of the three keywords: let, const, and var.

Top comments (0)