JavaScript Intermediate Day 1: Scope & Closures

Goal of this Day

Today you will learn:

By the end, you will understand how variables live and behave in JavaScript functions.

Step 1: Scope

Scope defines where a variable is accessible.

Step 2: Closures

A closure is a function that “remembers” the variables from the scope it was created in, even after that scope has finished.


function outer() {
  let count = 0;

  return function inner() {
    count++;
    return count;
  };
}

const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

Explanation:

Practice


function outer() {
  let count = 0;

  return function inner() {
    count++;
    return count;
  };
}

const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

Task

Create a counter function using closure that:

Example:


function createCounter() {
  let count = 0;

  return function() {
    count++;
    return count;
  };
}

const myCounter = createCounter();
console.log(myCounter()); // 1
console.log(myCounter()); // 2
console.log(myCounter()); // 3