Skip to content
This repository has been archived by the owner on Jan 24, 2023. It is now read-only.

Commit

Permalink
Add simple closure example
Browse files Browse the repository at this point in the history
  • Loading branch information
sicktastic committed Sep 12, 2017
1 parent 1e47327 commit f59082f
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions advance_js/closures.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Closure
// A function with access to its own private variables

// problem with global variables
// var count = 0;

// function countBirds() {
// count += 1;
// return count + ' bird';
// }

// function countDogs() {
// count += 1;
// return count + ' dogs';
// }

// function makeBirdCounter() {
// var count = 0;
// return function() {
// count += 1;
// return count + ' birds';
// }
// }

// function makeDogCounter() {
// var count = 0;
// return function() {
// count += 1;
// return count + ' dogs';
// }
// }

// Refactor
function makeCounter(noun) {
var count = 0;
return function() {
count += 1;
return count + ' ' + noun;
}
}

var birds = 3;

// outer function
function dogHouse() {
var dogs = 8;

// 1.0
// console.log(birds); // 3
// console.log(dogs); // 8
// This won't be avaliable outside the function

// inner function
function showDogs() {
// inner function has access to outer function
console.log(dogs);
}
return showDogs;
}

// 1.0
// console.log(birds); // 3
// console.log(dogs); // undefined

var getDogs = dogHouse();
getDogs(); //8

0 comments on commit f59082f

Please sign in to comment.