Skip to content

Instantly share code, notes, and snippets.

@greduan
Last active August 29, 2015 14:09
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 greduan/48bb89dd54dbd9cf5c83 to your computer and use it in GitHub Desktop.
Save greduan/48bb89dd54dbd9cf5c83 to your computer and use it in GitHub Desktop.
Quick JS file demonstrating closures very simply
var foo = 100;
console.log('first'); //=> 'first'
console.log(foo); //=> 100
(function () {
var foo = 200;
console.log('second'); //=> 'second'
console.log(foo); //=> 200
}());
console.log('third'); //=> 'third'
console.log(foo); //=> 100
var foo = 100;
console.log('first'); //=> 'first'
console.log(foo); //=> 100
function test() {
var foo = 200;
console.log('second'); //=> 'second'
console.log(foo); //=> 200
}
test();
console.log('third'); //=> 'third'
console.log(foo); //=> 100
var foo = 100;
console.log(foo); //=> 100
function test() {
console.log(foo); //=> 100
}
test();
(function () {
console.log(foo); //=> 100
}());
console.log(foo); //=> 100
var foo = 100;
console.log(foo); //=> 100
(function () {
var bar = 200;
console.log(foo); //=> 100
console.log(bar); //=> 200
}());
console.log(foo); //=> 100
console.log(bar); //=> ERROR
@Reedyseth
Copy link

On the first example like you saw $foo will use the values define on its own scope.

On the second example on https://gist.github.com/Greduan/48bb89dd54dbd9cf5c83#file-closures2-js-L15 the value will be 200. This is what I ready on the script, I will run it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment