Skip to content

Instantly share code, notes, and snippets.

@lyzadanger
Created March 26, 2015 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyzadanger/d31ecc156468a2c413da to your computer and use it in GitHub Desktop.
Save lyzadanger/d31ecc156468a2c413da to your computer and use it in GitHub Desktop.
Thinking about scope (for Sara)
'use strict';
var outerFunction, innerFunction;
outerFunction = function() {
innerFunction = function() {
console.log('inner');
};
console.log('outer');
};
outerFunction();
innerFunction();
'use strict';
function outerFunction() {
console.log('outer');
function innerFunction() {
console.log('inner');
}
}
outerFunction();
innerFunction();
'use strict';
function outerFunction() {
var mySecretValue = 42;
return mySecretValue;
}
var secret = outerFunction();
console.log(secret);
'use strict';
var secretKeeper, secret;
function outerFunction() {
var mySecretValue = 42;
return function() {
return mySecretValue;
};
}
secretKeeper = outerFunction();
secret = secretKeeper();
console.log(secret);
'use strict';
var secretKeeper, secret;
function outerFunction() {
var mySecretValue = 42;
return function() {
mySecretValue++;
return mySecretValue;
};
}
secretKeeper = outerFunction();
console.log(secretKeeper());
console.log(secretKeeper());

(You should be able to clone this gist and run node example[x].js for each JS file here to do the exercises).

  • What do you think will happen when you execute example1.js?
  • What happens if you comment out line 12 and run example1.js? Why?
  • What do think will happen when you execute example2.js? Did it work as you expected?
  • What would happen if you added a new line to the end of example3.js and console.log(mySecretValue);? Why?
  • What type is secretKeeper on line 12 of example4.js? How did it get assigned?
  • What code does secretKeeper() execute when it is invoked on line 13 of example4.js? What does it return and how?
  • What type is secret as of line 13 of example4.js?
  • What will log to the console in line 14 of example5.js? Line 15?
  • What is the lifecycle of mySecretValue in example5.js? How and when does it change value?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment