DEV Community

Cover image for Scoping in Javascript
Shubham_Baghel
Shubham_Baghel

Posted on

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

Top comments (0)