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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more