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 ;

Life cycle hook

In Angular, every component has a life-cycle, a number of different stages it goes through. Creates the component Renders the component Creates and renders the component children Checks when the component data-bound properties change, and  Destroys the component before removing it from the DOM ngOnChanges this method is called  once  on component’s creation and then  every time changes  are detected in one of the component’s  input  properties. export class MyComponent implements OnChanges { ngOnChanges(changes: SimpleChanges) { // Insert Logic Here! } }   ngOnInit Invoked when given component has been initialized. This hook is only called  once  after the first  ngOnChanges export class MyComponent implements OnInit { ngOnInit() { // Insert Logic Here! } }     ngDoCheck Invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component. export class MyComponent implements D

DOM(Document Object Model) and BOM(Browser Object Model)

DOM(Document Object Model) The DOM is the Document Object Model, which deals with the document, the HTML elements themselves, It organize the elements of the document in tree structure (DOM tree) and in the DOM tree, all elements of the document are defined as objects (tree nodes) which have properties and methods.When a web page is loaded, the browser creates a DOM tree for all the objects (Html elements) of that page. e.g. document and all traversal you would do in it, events, etc. A Simple DOM Tree BOM(Browser Object Model) The BOM is the Browser Object Model, which deals with browser components aside from the document,like history, location, navigator and screen (as well as some others that vary by browser). The Browser Object Model (BOM) in JavaScript includes the properties and methods for JavaScript to interact with the web browser. BOM provides you with window object, for example, to show the width and height of the window. It also includes the window.scre