Home/Tutorials/JavaScript/Scope, Closures, and this

0 of 3 saved

JavaScript5 min read

Scope, Closures, and this

Read this chapter, write the program on this page, then pass a short check to open the next one.

Where names live and what this means.

Scope, Closures, and this

Lexical scope decides which variables a function can see. A closure remembers variables from its outer scope. this depends on how a function is called (except arrows).

  • Inner functions can read outer lets/consts.
  • Closures power private state and callbacks.
  • Prefer arrows for callbacks when you want lexical this.
function makeCounter() {
  let n = 0;
  return () => {
    n += 1;
    return n;
  };
}
const c = makeCounter();
console.log(c(), c());

After you read this chapter, use Write (when available) and Quiz on this page to lock it in.