- 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:
letandconstinside{ }are only visible inside those braces. varignores block scope and leaks out ofifblocks 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.
varis hoisted asundefined.let/constthrow aReferenceErrorif 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.