Module1: How Closures Work

module1_writing_modular_code_with_functions
jason.zhu 2021-05-12 11:45:47 +10:00
parent c11b998681
commit c38c66a446
1 changed files with 11 additions and 4 deletions

15
app.js
View File

@ -1,5 +1,12 @@
let message = 'Hello';
if (message === 'Hello') {
var count = 100; // var is within global scope, when it's not within object or function
function setupCounter(val) {
return function counter() {
return val++;
}
}
console.log(count); // No reference error, which is dangerous
let counter1 = setupCounter(0);
console.log(counter1());
console.log(counter1());
let counter2 = setupCounter(10);
console.log(counter2());
console.log(counter2());