Wait, where is my variable defined?

Learn JavaScript scope so you always know where your variables are defined

You may have noticed that Head First JavaScript Programming is released! Now that the book is done, we’ve got a few more Head First JavaScript Programming teasers for you. The book is aimed at those of you who are learning JavaScript from the ground up, and our goal with these teasers is to tease out a few characteristics of the language that might surprise you, trip you up, or that you might want to pay special attention to as you learn.

Whether you’re coming to JavaScript from another language, or you’re learning JavaScript as your first language, the way scope works — that is, when and where your variables are defined — might surprise you. Scope in JavaScript isn’t always intuitive, and it’s easy to make some simple mistakes that can cause your code to work in unexpected ways.

Imagine you’ve written some JavaScript code (say, for a web page about dogs) that uses the variable fido. You want to create a dog simulator, and find that someone’s already written that code, and made it available as a library you can link to. So, you add a link in the head of your document to that library and… all of a sudden your code isn’t working any more. This scenario can happen easily because of the way JavaScript scope works.

In this installment of Head First JavaScript Programming Teasers, you’ll learn about the basics of scope, why it’s important to limit the number of global variables, how functions create scope, what “hoisting” is, and how to know where your variables are defined.

tags: , , , , , , , ,

Get the O’Reilly Programming Newsletter

Weekly insight from industry insiders. Plus exclusive content and offers.