Advanced Scope
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
Scope
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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?
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
You can 'hide' variables in functions (local scopes)
-OR-
make variables available everywhere (global scope).
- To have multiple for loops all using i as their iterator
- 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.
- Closures!! We'll get to this shortly. It's pretty cool.
Why would we want to hide something in local scope?
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
- 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?
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
- Local
- Global
- Nested Scopes
- Precedence
SCOPE-RELATED CONCEPTS
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
Note: keyword var is important here!
Local Scope
var global;
var func = function(){
var local = true;
};
func();
console.log(local);
console.log(global); //undefined
![](https://s3.amazonaws.com/media-p.slid.es/uploads/304195/images/1357698/Screen_Shot_2015-05-08_at_9.47.30_AM.png)
- 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.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
Global scope
- Global scope is for variables you want to be broadly accessible.
- Avoid putting things here unless you have to.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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...
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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!
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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!';
}
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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();
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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'
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
creating scopes
When are scopes actually created?
- Each invocation of a function runs completely separately from all other invocations of that function.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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!
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
Key takeaways
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
- Scope determines variable accessibility
- "Execution scopes" are created every time you invoke a function
Key takeaways
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
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
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
Exercise Time!
- Repo?
- TAs?
- Pairs?
- References?
- Slides
- The Internet!
- StackOverflow
![](https://s3.amazonaws.com/media-p.slid.es/uploads/362520/images/1635394/stucked.png)
Week 2: Advanced Scopes
By telegraphprep
Week 2: Advanced Scopes
An introduction to functional programming
- 881