Skip to main content

JavaScript Variable Scoping

There are two types of variables in JavaScript. 

  • Global variables have global access and are declared outside of any function.
  • Local variables are those declared inside of function.
  • Lexical Scoping(Nested JavaScript Function) means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope.
Global variable:-
Global variable declares & initialize outside the function, & accessible in from anywhere in the code.
The global variable always stored in memory even function execution finish, it always keeps in memory or always accessible from anywhere in the code.
Example 1
var message= "hello i am global variable";     //global variable  
function a(){  
console.log(message);  // output: hello i am global variable
}  
function b(){  
console.log(message);  // output: hello i am global variable
} 
function a()
function b()

In above example message is a global variable, it can be accessed from both function function a & .function b
Local variables:-
All local variables have function-level scope, any variable declared inside a function is a local variable, it is not accessible outside the function. local variable store in stack frame within function, while function starts execution and removed from memory once it done with execution.
Example 2
var name = "Jhon";
function showName () {
    var LastName = "Jack"; // local variable 
    console.log (LastName); // Jack
    console.log (name); //Jhon
}
console.log (name); // Jhon: the global variable
console.log(LastName) //Uncaught ReferenceError: LastName is not defined

In this above example name is global variable so it can be accessed form inside function & outside of a function , & LastName is local variable for showName function, so it can be accessible inside the function only where variable declared. when I try to access LastName outside of the function it throws error ‘LastName is not defined’. so we can look scope of local variable & Global variable.

Inside a function, if a variable is initialized (assigned a value) without first being declared with the var keyword, it is automatically added to the global context and it is thus a global variable.
Example 3
//If you do not declare your local variables with the var keyword, they are part of the global scope
var name = "Jhon";
function showName () {
    console.log (name); //Jhon
}  
function showOrdinaryName () {  
    name = "Johnny"; // name is not a local variable, it simply changes the global name variable
    console.log (name); //johnny
}
showName (); 
showOrdinaryName (); 
console.log (name); // Johnny

In this above example name is global variable so it can be accessible from showName function. in showName function name initialize but did not declared inside a respective function, so it becomes Global variable. So when I try to access name variable outside the function the output would be ‘Johnny’ so it becomes a global variable.
Example 4
var name = "Jhon";
function showName () {
    console.log (name); //jhon
}  

 showName(); // Johnny Evers
function showOrdinaryName () {  
// The solution is to declare your local variable with the var keyword
    var name = "Johnny"; // Now name is always a local variable and  it will not overwrite the global variable
    console.log (name); // Johnny
}
showOrdinaryName ()
    console.log (name); //Jhon

Always declare your local variables before you use them. Otherwise, it becomes Automatic global variable.
JavaScript does not have block-level scope. ECMAScript 6  supports block-level scopes via the let keyword.
This means inside of a block structure like “if ” condition block (curly braces) it does not create any local variable, if we create a new variable inside if condition it will become a Global variable. ECMAScript 6 is support block-level scopes via the let keyword.
Example 5
var name = "jhon";
// the blocks in this if statement do not create a local context for the name variable
if (name) {
    name = "Jack"; // this name is the global name variable and it is being changed to "Jack" here
    var lastName ="Smith"
    console.log (name); // Jack: still the global variable
}
// Here, the name variable is the same global name variable, but it was changed in the if statement
console.log (name + lastName ); // Jack Smith
Local Variables Have Priority Over Global Variables inside Functions
If you declare a global variable and a local variable with the same name, the local variable will have priority when you use variable inside function.
Example 6
var name = "Paul";
function users () {
    // Here, the name variable is local and it takes precedence over the same name variable in the global scope
var name = "Jack";
console.log (name); //jack
}
users (); 

Comments

Post a Comment

Popular

JavaScript type hoisting with variable function Expression

JavaScript type hoisting with variable function Expression Hoisting is JavaScript default behavior to moving declaration on the top. Variable can be used before its declaration. To understand this, first we need to understand of hoist meaning, hoist means “raise(something) by means of ropes & pulleys”. now we can relate hoisting with JavaScript. JavaScript interpreter moves all declaration on the top at runtime. It is best practice to declare all variable at the top of their respective scopes. , JavaScript is loosely syntax language so it will not throw any error at runtime if the variable used before its declaration. But JavaScript does not allow variable used before its declaration in “use strict” mode. Example 1 In this example, we can see in a normal scenario, when y has declared & then used. in this case, it will give output 10 as excepted. <p id= "demo" ></p> <script> var y; //Declare y y = 10 ; ...

JavaScript Closure

What is closure? It is my personal experience, I have never understood closure, I have read many articles & have seen many videos. Finally, I understood sometimes we even used a closure without realizing we were using a closure. First, understand the meaning of closure “an act or process of closing something”, now we can relate closure in javascript, closure is an inner function which wraps inside the outer function, which can access outer function scope & global function scope. for scoping you can read my previous blog:- http://uisource.blogspot.com/2018/08/javascript-variable-scoping.html why do we create? Global variables can be made local (private) with closures. To avoid the usage of global variables, use the local variables and wrap your code in the closure. A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain(Lexical scoping). The closure has three scope chains: it has access to its own scope (variables define...