Scope

Scope

what variables/functions are accessible

Global Scope

variables declared in the global scope

are available everywhere.

The global object in the browser environment is window

The global object in node environment is global

// forgetting to use the `var` keyword
// will create a new global variable
//   does not work in strict mode
name = "Buzz";

// in node
global.name;  // Buzz

// in browser
window.name;  // Buzz

Local Scope

declaring variables allow it to be accessible

within the current scope and every child scope

 

child scopes can only be created with functions

// declare a local variable in the current scope
var friend = "Lightyear";

// create a child scope
function buddy(){
  // has access friend
}

Local Scope

variables and functions declared in a child scope

is not accessible from outside of that child scope

function unfriendly(){
  // declaring a variable in child scope
  var secret = "hunter2";
}

// global scope does not have access to `secret`
secret; // ReferenceError: secret is not defined

function anotherChild(){
  // also cannot see `secret`
  secret; // ReferenceError: secret is not defined
}

Local Scope

deeper child scopes have access to the variables/functions in it's parent and it's parent, and so on

var announcement = "Good News everyone!";

function unfriendly(){
  var secret = "hunter2";

  // creates another child scope
  function veryPrivate(){
    // that has access to `secret` and `announcement`
  }
}

Local Scope

what is accessible from the 3 scopes here?

var announcement = "Good News everyone!";

function unfriendly(){
  var secret = "hunter2";
  
  function veryPrivate(){
    var verySecret = "Passw0rd";
  }
}
  • global scope
  • unfriendly()
  • veryPrivate()

scope

By Jon Borgonia

scope

  • 1,988