28: Scope and Closures

In this exercise you will learn about the two complementary topics of scope and closure. Scope is the idea that variables declared at different nesting levels will not interfere with each other. A closure when you create a function while inside another function, it will carry with it the entire outer scope of where it was defined. These two concepts are very powerful when you start using them in the next exercise on partial application.

Var Sucks

Before we can talk about scope, we need to talk about var vs let. In the early days JavaScript had only two scopes where a variable was defined either globally or inside a function and that was it. This caused many bugs because the normal way scope works is inside every block structure, like an if-statement or while-loop. In this example I show you a simple function that declares a variable using each style, and then change it inside an if-statement to demonstrate the flaw.

{{ ork.js() }}

Learn JavaScript Today

Register today for the Beginner Basics course and get the new releases by just paying the difference. There's also special discounts for existing customers when new courses are released.


Still Not Sure? Check out more curriculum!