What you will learn:
1) Download an online version of the “Hello World” script from the Internet
2) Open up Firefox and right click in the browser window and choose “view page source” to look at the HTML code. (This will also work in IE – I’m just using Firefox as an example).
3) Once you’re in the HTML source, look for the “Hello World!” line:
4) When you’ve found it, copy/paste that line into Notepad. You should then have something similar to this:
5) Now that you’ve got your “Hello World!” script open in Notepad, look for other “Hello World” scripts on the web and copy/paste them into your Notepad file. Keep doing this until you have at least 10 or so “Hello World!” scripts in the document.
Take this example:
If you were to hover over the variable “name”, you would see that it is a global variable. This means that it can be accessed anywhere in the script. Because of hoisting, “name” will be assigned to whatever is inside the quotes where it is used. In this example, it’s assigned to what’s between the quotes when a function is called. This means that inside the function call code, we can still access name:
Now let’s take a look at situations where we don’t have hoisting:
I’ve added a new line in here which assigns another variable called “yay” to whatever number ends up being returned in the line above. Because of hoisting, we can’t do this:
If hoisting was not in use, then the script would look more like this:
To properly use these tips, you’ll need to know about scope and closures. Scope refers to when and where a variable is created and what it’s used for.
Closures are essentially the way that you can access variables that are outside of a function, without having to use global variables.
First of all, global variables should be avoided as much as possible. If they exist at all, then they should be very small. For example:
Global variables should also be avoided if possible. It’s better to have them in functions and use function scope instead. A good example is as follows:
Alternatively, you can put global variables into “namespaces”. Namespaces are basically two or more global variables that you group together so that you can keep track of one object instead of multiple objects (one for each namespace).