Agyan
adda
Run
Reset
Copy
JavaScript Tutorial › JS Scope › Block scope and a closure
Back to tutorial
Code
Edit, then press Run or Ctrl+Enter
<button id="btn">Clicked 0 times</button> <pre id="out"></pre> <script> const site = 'AgyanAdda'; // global if (true) { let inside = 'only in this block'; } document.getElementById('out').textContent = 'site: ' + site + '\ninside: ' + (typeof inside); function makeCounter() { let count = 0; // private to the closure return () => ++count; } const next = makeCounter(); document.getElementById('btn').onclick = function () { this.textContent = 'Clicked ' + next() + ' times'; }; </script>
Result