One of the fundamental aspects of Javascript is variable scope, and in this lesson we'll dive into how variable scope works when defining variables with var
, let
, or const
.
The three main takeaways are:
Inner scope can always read values defined in an outer parent scope.
Outer scope cannot read values defined in an inner scope (except when defined with var
).
The var
scope-bleed issue can be overcome using immediately-invoked function expressions (IIFEs).
Yoni Weisbrod: [0:00] In JavaScript, we can define variables in three ways using either var, const, or let. I'd like to think about the differences between these in three primary ways, and that is how they handle scoping, how they're hoisted, and whether you can redeclare and reassign values.
[0:16] Today in this video, we're going to handle scoping. The first thing to know about scope is that if we define a value in an outer parent scope, inner scopes will always have access to this value. It doesn't matter if we're using var, let, or const, the inner scope will always have access to this value.
[0:41] Where we get into problems is if we try to do the reverse. Let's say we define animal inside the scope, and then we try to read its value outside the scope. We can see that we get a ReferenceError and we'll get this error if we use const or let, but we won't get this error if we use var. That's because scope defined by var creeps out of its block scope.
[1:04] In essence, block scope doesn't exist for var. When I say block scope, I literally mean anything inside a block or inside parentheses. You can declare a variable inside parentheses, and that will effectively be scoped to these parentheses.
[1:21] There are other ways to do block scope as well, and you can identify these in code when you see the parentheses. For instance, in an if statement, anything inside the parentheses will be block scoped.
[1:33] Using block scope, you can keep your code a little more clear and predictable, but what did people do before let and const came around if we wanted to limit the scope of a variable? The answer is that we would use function scope.
[1:46] If we put this in a function, then we can see that the scope does not creep out anymore. Again, we have a ReferenceError here, so we can't read the inner scope anymore. Function scope is a very effective way to limit the scope of any type of variable, var, let, const.
[2:06] The problem is it's a bit ugly because if there's code here that you want to run as well, we need to call the function, which is inconvenient to have to do everywhere you want to limit scope.
[2:17] The solution for this is to use something called an immediately invoked function expression, where we simply put brackets around our function and then call it right away. The IIFE used to be fairly common before let and const came around.