Sample Video Frame

Created by Zed A. Shaw Updated 2024-07-21 04:57:00

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.

View Source file code.js Only

Previous Lesson Next Lesson

Register for Learn JavaScript the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.