DEV Community

Oreoluwa Soyoye
Oreoluwa Soyoye

Posted on

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"
Enter fullscreen mode Exit fullscreen mode

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay