DEV Community

Cover image for Scoping in Javascript
Shubham_Baghel
Shubham_Baghel

Posted on

2

Scoping in Javascript

Scoping is mainly deals where variables,functions and objects are accessible in your code during the execution of program.The scope of a variable accessibility is controlled by the where the variable declaration is actually done in #JavaScript.

Scoping:

JavaScript rules with three different keywords to declare a variable which will deals with scoping in terms of functional block scoping with different declaration of variable.

In JavaScript has two scopes:
1.Global Scope
2.Local Scope

1.Global scope:
Variables which are defined outside any function, block scope have global scope. Variables in global scope can be accessed anywhere.

var test = "hello"; function sayHello() { // Initialize a local, function-scoped variable var test = "world"; console.log(test); } // Log the global and local variable console.log(test); sayHello(); console.log(test);

2.Local Scope
Variables with Local scoped are only accessible within their local scopes.Variables declared within a function are in the local scope.Local scope is also called function scope because local scope is created by functions in JavaScript.Variables in the local scope are only accessible within the function in which they are defined.

when we go through below 'let' — which is block scope variable — It will perform same action over the block.

function sayHello() { let myname = 'User1' console.log(myname); // 'User1' } sayHello(); console.log(myname); // myname is not defined

Conclusion:

1.Global Scope variables will be access everywhere.
2.'const' and 'let' are block scope variables which will be access in block only.

Alt Text

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay