Transcript from the "let & Scope" Lesson
>> We had a question. Is there some way to force the variable I'm dealing with in my local scope of my function, to exist outside of it in the wider scope, in the global scope. All right, that was the question am I paraphrasing, okay. So let is one kind of hack we could use to do something like this.
[00:00:25] But this can be kind of dangerous. So for example, let's say we have a variable called feeling that has a value of free. Because it's a let variable, that means I can change what it points to. So if I have a function trap within that scope. I can do an assignment to the variable feeling, which was created in the outdoors global scope, and assign it to a new value boxed in.
[00:01:01] So now the question is outside of that function, once I've run the function trap, what is going to happen when I do console.log(feeling). What do you guess.
>> Boxed in.
>> Boxed in. Any other guesses? Let's find out. Oops, all right, so we have our feeling free, just checking free, cool.
[00:01:26] We have our trap function. Nothing happened. Didn't call it yet. Let's call it, okay. And now let's check what feeling is, it is indeed boxed in. Okay, let's go to the whiteboard and talk about what just happened. So we had our global scope We declared a variable feeling and what did this point to initially?
>> The string free, okay. And because it's let, we have a flexible arrow here that can be changed. Then we had our function, what was it called, trap? Which creates its own new scope with tinted windows on it. But in this case, within there, we had a reference to the variable feeling.
[00:03:14] So that change, the pointer change from free to boxed in, is actually going to persist outside of this function scope. So this is kind of a weird thing that we need to be careful of when we're using variables with let. Which means that we can reassign them. Now, if we had tried this with const, what would've happened?
[00:03:41] Error can't reassign, can't reassign const. So wouldn't matter whether we were inside or outside of the function. We can't reassign a const variable. Another reason why it's often useful to use const. So that accidentally somebody doesn't mess with your variables while you're not looking. Okay, any questions on that?
[00:04:33] So initially it was pointing out one string. We didn't change that string, we conjured up a new string. Got rid of that old arrow and then created a new arrow pointing to a different value. So we did not actually modify the string free. We modified what the variable points to.
[00:05:51] And that is going to affect which variables we can reference, where and when. But we can see out of the limo. So that's why we were able to modify our feeling that was declared outside of this trap function. And it's also how we were able to, in our isCorrect function.
[00:06:12] We were able to evaluate fact, which was a variable declared in the wider context, not inside of the function.