Advanced Scope

Creative Commons License

Scope

It's all about variable access...

Scope determines what variables are available for you to use at any given point in your program.

What is scope and why does it matter?

You can 'hide' variables in functions (local scopes)

-OR-

make variables available everywhere (global scope). 

  1. To have multiple for loops all using i as their iterator
  2. Avoid polluting the global namespace
    • Say you're Facebook, and you have millions of lines of code. You're probably going to use the variable 'likes' to mean different things in different parts of your code. 
  3. Closures!! We'll get to this shortly. It's pretty cool.

Why would we want to hide something in local scope?

  • There's only one way to create local scope: inside a function body.
  • Each function body has it's own local scope.
    • This is the only way to create local scope. 
    • Nothing else creates local scope. Only function bodies. 

How do we create local scope where we can hide a variable?

  • Local
  • Global
  • Nested Scopes
    • Precedence

SCOPE-RELATED CONCEPTS

Local Scope

var func = function(){
  var local = true;
};
func();

console.log(local);
  ReferenceError: local is not defined
  • What does local scope mean? 
  • It simply means that variables declared in a function are 'hidden' from the rest of the program
  • That is, they only exist in this scope. 

Note: keyword var is important here!

Local Scope

var global;
var func = function(){
  var local = true;
};
func();
console.log(local);


console.log(global); //undefined
  • A variable will be undefined if it exists (was declared) in that scope but hasn't been defined yet.
  • A variable will throw this breaking ReferenceError if it does not exist in that scope. 

Global scope

  • Global scope is for variables you want to be broadly accessible.
  • Avoid putting things here unless you have to.
var x = 'global!';
//inside a function
function addToGlobalScope(){
  y = 'global here, too!';
}
//inside a function
function addToGlobalScope(){
  y = 'global here, too!';
}

Global Scope

  • Using the keyword var creates a variable and assigns it to the current scope. 
  • Not using the var keyword puts it in the global scope, no matter where it is in your program. 
var x = 'global!';
//inside a function
function addToGlobalScope(){
  y = 'global here, too!';
}
//inside a function
function addToGlobalScope(){
  y = 'global here, too!';
}

Global Scope

What gets print to the console?

Let's walk through the code as the JS interpreter...

console.log(y) //???
var x = 'global!';
//inside a function
function addToGlobalScope(){
  y = 'global here, too!';
}
//inside a function
function addToGlobalScope(){
  y = 'global here, too!';
}

Global Scope

REMEMBER: y is not declared until addToGlobalScope is called!

addToGlobalScope();
console.log(y); //???
var x = 'global!';
//inside a function
function addToGlobalScope(){
  y = 'global here, too!';
  var z = 'using var inside a 
  function body makes this local';
}

Global vs. Local Scope

The var keyword is important!

It creates a variable and then assigns it to the current scope. 

//inside a function
function addToGlobalScope(){
  y = 'global here, too!';


}

Keyword Var

  • Always use the var keyword to create new variables. Funky, unexpected things happen when you don't. 
  • Plus, it just makes your code easier to read. 
  • This is one of those areas of engineering where just following a simple rule (always use the var keyword when declaring a new variable) will save you a lot of effort and future pain. 
  • You can spend time learning more if you want, or you can just always use the keyword var.

security clearance Example

var aliensExist = false; //global scope














console.log(aliensExist); //false
var secretClearance = function() {
  var aliensExist = 'only sort of...';
  
  




  
  console.log(aliensExist); //'only sort of...'
};
secretClearance();
  var superTopSecretClerance = function() {
    var aliensExist = 'They totally do';
    console.log(aliensExist) //'They totally do'
  };
  superTopSecretClearance();
  

Let's walk through how this code gets executed...

Top secret security clearance review

  • When you have no security clearance, you're stuck looking at only public information.
  • When you have Secret clearance, you check that information first before checking the public info.
  • And when you have Super Top Secret clearance, you check Super Top Secret info first before checking Secret, before checking public. 

Ingredient of the day example

var globalRequirement = 'pies';

var cookingBonanza = function(ingredient) {
  










  console.log('I am cooking ' + globalRequirement + ' with ' + ingredient);
};
cookingBonanza('collard greens');
//'I am cooking pies with guacamole'

Don't worry, I don't get to do much of the cooking in my house.

var globalRequirement = 'pies';

var cookingBonanza = function(ingredient) {
  
  var obstinateChef = function() {
    var ingredient = 'guacamole'; //we are 'masking' ingredient here
    //we can still access the global globalRequirement variable
    console.log('I am cooking ' + globalRequirement + ' with ' + ingredient);
  };
  




  console.log('I am cooking ' + globalRequirement + ' with ' + ingredient);
};
cookingBonanza('collard greens');
var globalRequirement = 'pies';

var cookingBonanza = function(ingredient) {
  
  var obstinateChef = function() {
    var ingredient = 'guacamole'; //we are 'masking' ingredient here
    //we can still access the global globalRequirement variable
    console.log('I am cooking ' + globalRequirement + ' with ' + ingredient);
  };
  obstinateChef();
  
  //notice that our change to ingredient (using the var keyword!) doesn't
  //ever have to leave it's scope. the ingredient variable 
  //inside obstinateChef exists only in that scope. 
  console.log('I am cooking ' + globalRequirement + ' with ' + ingredient);
};
cookingBonanza('collard greens');
//'I am cooking pies with guacamole'
//'I am cooking pies with collard greens'

creating scopes

When are scopes actually created?

  • Each invocation of a function runs completely separately from all other invocations of that function. 
var nameMaker = function(name) {
    return {name: name};

};

var albreyObject = nameMaker('Albrey'); // {name: 'Albrey'}
var shannaObject = nameMaker('Shanna'); // {name: 'Shanna'}

// each time we invoke nameMaker, a new scope is created

passing variables into scopes

Arguments are values that are passed into the local scope of the corresponding function

var nameMaker = function(name) {
    return {name: name};

};

var albreyObject = nameMaker('Albrey'); // {name: 'Albrey'}
var shannaObject = nameMaker('Shanna'); // {name: 'Shanna'}

// 'Albrey' and 'Shanna' become local variables to nameMaker 
// when passed into the function

returning variables from functions

The only way to access a local variable from the global scope is by returning it from the function

var nameMaker = function(name) {
    var obj = {name: name};
};

var nameMaker2 = function(name) {
    var obj = {name: name};
    return obj;
};
var albreyObject = nameMaker('Albrey'); // undefined
// We can't access obj in nameMaker because we didn't return it

var shannaObject = nameMaker2('Shanna'); // {name: 'Shanna'}
// We can access obj in nameMaker2 because we returned it

how do we create scope review

  • What is the only way of creating local scope in JavaScript? 
    • Using the var keyword within a function body.
  • Nothing else creates local scope!

how do we create scope review

  • For those of you coming from other languages, note that block scope does not exist in JS. 
  • For those of you who only know JS- know that people coming from other languages will be slightly confused by not having block scope. 
  • Don't worry about this; just keep doing what you already are. 

Key takeaways

  • Scope determines variable accessibility
  • "Execution scopes" are created every time you invoke a function

Key takeaways

Lexical Scoping, nested functions, and precedence

  • In JS there is only function scope, no block scope
  • Nested functions have access to variables declared in their outer scope
  • Variable lookup starts in local scope then goes outward

Key takeaways

Local vs Global

  • Local scope variables - declared within a function body and only accessible within that function
  • Global scope variables - any that are not declared within a function body 
    • if you don't use the "var" keyword in a function, the variable gets put on the global scope

Questions

Exercise Time!

  • Repo?
  • TAs?
  • Pairs?
  • References?
  • Slides
  • The Internet!
  • Google
  • StackOverflow

Week 2: Advanced Scopes

By telegraphprep

Week 2: Advanced Scopes

An introduction to functional programming

  • 881