Java Script Scope

Scope , JS code में variable की accessibility को determine करता है।

Java Script में तीन प्रकार के Scope होते है।

  1. Block Scope
  2. Function Scope
  3. Global Scope

Block Scope

Block Scope को ES6 (2015) में introduced किया गया।
ES6 में दो नए JS keyword let और const को भी introduced किया गया जो block scope प्रोवाइड करते है।
let और const कीवर्ड की सहायता से जब किसी वेरिएबल को { } ब्लॉक के अंदर declared किया जाता है तो उस वेरिएबल को हम block के बाहर access नहीं कर सकते।

   {
        let x = 87
        const y = 56

console.log(x);              // O/P:  87
console.log(y);              // O/P: 56
    }

 console.log(x);             // reference error :  can't access outside the block
 console.log(y);             // reference error  :   can't access outside the block

यदि var कीवर्ड की सहायता से किसी वेरिएबल को { } ब्लॉक के अंदर declared किया जाता है तो उस वेरिएबल को हम block के बाहर भी access कर सकते। क्योकि वर कीवर्ड का block scope नहीं होता है।

 {
       var x = 87
       console.log(x);           // O/P: 87
    }

 console.log(x);                // O/P: 87 
//  access outside the function

Function Scope

function scope में function के अंदर define किये गए variable को function के बाहर access नहीं कर सकते है।
var let और const keyword तीनो का function scope होता है इसलिए इन कीवर्ड की मदद से define किये गए variable फंक्शन के बाहर access नहीं होंगे।

function xyz(){
    var z = 25

    let y = 100
    let x = 200
    console.log(z);         // 25
    console.log(y);         // 100
    console.log(x);         // 200
}
xyz()
console.log(z);          // reference error 
console.log(y);          // reference error
console.log(x);          // reference error
// can't access outside the function

Global Scope

Global scope में variable को Globally (अर्थात function और block के बाहर ) declare किया जाता है।
Global Scope variable को जावा स्क्रिप्ट प्रोग्राम में कहीं भी access कर सकते है।

var a = 10                // Global Variable
let b = 5                 // Global Variable
const c = 15              // Global Variable
 function abc(){
    console.log(a);
    console.log(b);
    console.log(c);
 }
 abc()
console.log(a);
console.log(b);
console.log(c);
// global variable access anywhere in JS Code