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 ; ...

Building Block of Angular

The main building blocks for Angular are modules, components, templates, metadata, data binding, directives, services, and dependency injection. Below mentioned are the main building blocks of an Angular application: - Modules  group components logically within the project. Angular basically is a modular framework where every block of functionality is encapsulated within a module and exposed outside within the project as a service. There are two types of modules one is encapsulating block of function within a single component and the other is encapsulating block of function within single or group of components by providing exposure in a unified manner via an interface. Components  help in controlling UI block and also it provides data and logic. It represents a unique "View" and "View Model" in MVVM pattern or exactly like what Controllers do in Angular 1. The "V...

HTML Basic

HTML (Hypertext Markup Language) Basic What is HTML ? HTML invented by Tim Berners-Lee in 1990. HTML stands for hypertext markup language. Web browsers receive HTML documents from a web server or from local storage and render the documents into multimedia web pages .We can create web page with different elements like audio, video, image, tables, link, list & text etc, with CSS & JavaScript. version of HTML There are 6 version of HTML HTML Version Year HTML 1991 HTML 2.0 1995 HTML 3.2 1997 HTML 4.01 1999 XHTML 2000 HTML 5 2014 (Latest version) Latest version of HTML Latest version of html is HTML 5.0 , in latest version of html provided new tags for multimedia support. Now we are creating web page  index.html  How we can create Web page <!DOCTYPE html> < html > < head > < title > This is my First Web Page </ title > </ head > < body > < h1 > My First heading ...