JavaScript Scope

JavaScript Scope


JavaScript Scope
The scope of a variable is region of your program in which it is defined. JavaScript will have only to scopes. 
Scope- The scope of a variable is region of your program in which it is defined. JavaScript will have only to scopes. the enclosing context values and expressions are associated. 
  • essentially, the visibility of various identifiers in a program
Why scope 
  • Controls the visibility of variables and parameters.
  • A programmer should know about scope to prevent naming collisions and ambiguity.
Why scope in JavaScript 
  • JavaScript is NOT “some other language”
  • Unlike other languages like C, C++ JavaScript doesn’t support block level scope
  • Supports function level scope
There are three types of scope in JavaScript:
  • Block scope
  • Function scope
  • Global scope
Block scope
A block scoped variable means that the variable defined within a block will not be accessible from outside the block. A block can reside inside a function, and a block scoped variable will not be available outside the block even if the block is inside a function.
Example
For (var i = 0; i <=0; i++) {
    // block code
Variables declared inside a { } block can be accessed from outside the block.
Function Scope
In Function Scope each function creates a new scope.
 In Function scope variables defined inside a function are not accessible (visible) from outside the function.
In Function Scope variables declared with varlet and const are quite similar when declared inside a function.
Example
function vehicle() {
  var vehicalName = "car";   // Function Scope
}
Global Scope
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program.
Example
var x = 2;       // Global scope