Javascript and Scopes - MichaelChorak/projectTech GitHub Wiki

Wat zijn scopes?

Een scope van een variabel wordt bepaald door de locatie van de variabel. JavaScript heeft 2 scopes; GLOBAL en LOCAL scopes.

Een variable die gedeclareerd wordt buiten de functie wordt gezien als een globale scope en deze is overal toegankelijk. Elke functie heeft zijn eigen scope, dus als je in een bepaalde functie een variabele zou declareren dat zou betekenen dat het een Local scope variabel is.

var locales = {
  europe: function() {          // The Europe continent's local scope
    var myFriend = "Monique";

    var france = function() {   // The France country's local scope
      var paris = function() {  // The Paris city's local scope
        console.log(myFriend);
      };

      paris();
    };

    france();
  }
};

locales.europe();
var test = "I'm global";

function testScope() {
  var test = "I'm local";

  console.log (test);     
}

testScope();           // output: I'm local

console.log(test);     // output: I'm global

Bron