• No results found

How JavaScript Processes Variables

    alert(text);

}

checkWeight(6000);

The behavior of this checkWeight function is identical compared to what you saw a few moments earlier.

To repeat, there are only two scopes you need to keep track of. The first is the global scope where what you are declaring is completely outside the grip of a function. The second is the local scope where what you are declaring is enclosed by whatever function you are inside.

NOTE

The latest version of JavaScript (part of the ECMAScript 6/ES2015 improvements) introduces support for the let keyword that allows you to declare variables that are block scoped:

var x = 100;

If you thought the earlier block scoping logic was weird, wait till you see this one.

Take a look at the following code:

var foo = "Hello!";

function doSomethingClever() {     alert(foo);

ptg18144529     var foo = "Good Bye!";

    alert(foo);

}

doSomethingClever();

Examine the code in detail. What do you think is shown in the two highlighted alert function calls? Given what is going on, you may answer Hello! and Good Bye! However, if you test this code out, what you will actually see is undefined and Good Bye! Let’s look at what is going on here.

At the very top, we have our foo variable that is instantiated to Hello!. Inside the doSomethingClever function, the first thing we have is an alert that should show the value stored by the foo variable. A few lines below that, we re-declare the foo variable with a new value of Good Bye!:

var foo = "Hello!";

function doSomethingClever() {     alert(foo);

    var foo = "Good Bye!";

    alert(foo);

}

doSomethingClever();

Because our first alert comes before the foo variable re-declaration, the logical assumption is that foo’s original value of Hello! will be what gets shown. As you saw earlier, that isn’t the case. The value of foo when it hits the first alert is actually undefined. The reason for this has to do with how JavaScript deals with variables.

When JavaScript encounters a function, one of the first things it does is scan the full body of the code for any declared variables. When it encounters them, it initializes them by default with a value of undefined. Because the doSomethingClever function is declaring a variable called foo, before the first alert even hits, an entry for foo is created with a value of undefined.

Eventually, when our code hits var foo = "Good Bye!", the value of foo is properly initialized. That doesn’t help our first alert function, but it does help the second one that follows the re-declaration of foo. All of this has a name. It is known as hoisting or variable hoisting!

ptg18144529 Keep this little quirk in mind if you ever run into a situation where you are

re-declaring variables into a local scope like this simple example highlighted.

Tracking down why your variables aren’t behaving as expected isn’t fun, and hopefully this tidbit of knowledge will come in handy.

Closures

No conversation about variable scope can be wrapped up without discussing closures. That is, until right now. I am not going to explain closures here, for it is important and involved enough to require its own chapter. That chapter…is coming up next!

Given that this section is titled “Closures,” I’ll just do my usual closing song and dance here itself:

Well, that concludes this topic of variable scopes. This topic seems very simple on the surface, but as you can see, there are some unique characteristics that take some time and practice to fully understand.

I am not good at conclusions…or singing and dancing. I get that, and they are all on my bucket list. I swear!

THE ABSOLUTE MINIMUM

Where your variables live has a major impact on where they can be used. Variables declared globally are accessible to your entire application. Variables declared locally will only be accessible to whatever scope they are found in. Within the range of global and local variables, JavaScript has a lot going on up its sleeve.

This chapter gave you an overview of how variable scope can affect your code, and you’ll see some of these concepts presented front-and-center in the near future.

ptg18144529

TIP

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun i nteractive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!

ptg18144529

ptg18144529

8

Understand what closures are

Tie together everything you’ve learned about functions, variables, and scope

CLOSURES

By now, you probably know all about functions and all the fun functioney things that they do. An important part of working with functions, with JavaScript, and (possibly) life in general is understanding the topic known as closures. Closures touch upon a gray area where functions and variable scope intersect (see Figure 8.1).

ptg18144529 FIGURE 8.1

The intersection of functions and variable scope.

Now, I am not going to say any thing more about closures, as this is something best explained by seeing the actual code. Any words I add right now to define or describe closures will only serve to confuse things. In the following sections, we’ll start off in familiar territory and then slowly venture into hostile areas where closures can be found.

Onwards!

Related documents