Recap

Grade 9, page 11 of 11. A one-minute read.

  • Scope is where a variable can be seen and used.
  • Global scope: variables created outside everything, visible everywhere. Use as few as possible.
  • Function scope: variables (and parameters) created inside a function, visible only inside it.
  • Block scope: let and const inside { } are only visible inside those braces.
  • var ignores block scope and leaks out of if blocks and loops. Another reason to avoid it.
  • Shadowing: an inner variable with the same name hides the outer one.
  • The scope chain: JavaScript looks for a variable in the current scope, then outward, level by level. Never inward.
  • Hoisting: function declarations can be used before they're written. var is hoisted as undefined. let/const throw a ReferenceError if used too early (the temporal dead zone).
  • A closure is a function that remembers the variables from where it was created, even after that outer function has finished.
  • Closures are great for private data, function factories, and remembering state.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning