Welcome Guest! (App Version 3.1)

websitnero logo name

Types of Scope

Types of Scope in JavaScript

In JavaScript scope can only be of 2 types:

  • Global Scope
  • Functional Scope (Local Scope)

There is no 3rd type of scope in JavaScript (we are not talk of ES6 keywords: let & const).

Note: "Local Variables Have Priority Over Global Variables in Functions."

Note: "Any variable declared or initialized outside a function is a global variable, and it is therefore available to the entire application."

Note: " 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."

Global Scope

Any variable that is defined without 'var' keyword inside an inner function, or any variable defined right into script without going inside any function gets the global scope. It becomes a part of window.object property and can be accessed globally.

Example

<script>

var a = 10; 

function alpha(){
  var b = 5;
  alert("value of a inside: " + a);
  alert("value of b inside: " + b);
}

alpha();
alert("value of a outside: " + a); 
// alert("value of b outside: " + b); //This would give error 

//Here variable a got global scope, b got local inside function alpha
//'b' is not recognized outside alpha's functional scope at all 

</script>

Functional Scope

Any variable that is defined along with 'var' keyword inside a function gets functional scope. JavaScript has functional scope meaning that any variable bound between function has its life-cycle and visibility inside that particular function only. Outside the function, the variable cannot be accessed at all. The only method if any case is via 'Closures'.

Example

<script>

var a = 10; 

function alpha(){
  var b = 5;
  alert("value of a inside alpha: " + a);
  alert("value of b inside alpha: " + b);
}

function beta(){
  var c = 15;
  alert("value of a inside beta: " + a);
  alert("value of c inside beta: " + c);
}

alpha();
beta();
alert("value of a outside fn: " + a); 
//alert("value of b outside fn: " + b); //This will give error is b is unknown outside alpha
//alert("value of c outside fn: " + c); //This will give error as c is unknown outside beta

</script>
WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.