JavaScript 101: Variable Lifetime and Scoping


So as I said in my previous post, I decided to get re-introduced to JavaScript in a very in-depth way. Searched for a book on the internet. Found that Head First JavaScript is a good one which covers all the basic and some advanced topics and does so in a fun and engaging way. Decided to go with it.

Variable Scoping and Lifetime
This is probably the most read topics of all time whenever learning any language. Still, it is also the most ignored topic of all time. I did read the rules for scoping and lifetime for all the languages I learnt C, Java, but somehow the entire thing didn’t stick. I decided to once and for all “get” this and move on.
There are basically two types of scopes:
  1. Global: declared outside functions
  2. Local: declared in functions
That’s it. It’s that simple. Also, we should always use keyword var while declaring variables, else declarations (even those in functions) will be considered global! Major pitfall.

JavaScript does not have block level scope
Yes! Consider the following code in C/Java:
for (int i = 0 ; i < x ; i++) {}

Here, i is a variable which is declared locally to the loop. After the loop exits, there is no way you can retrieve the value of i.
However, consider the functionally same code in JS:
for (var i = 0 ; i < x ; i++) {}



In this code, the declared variable i is a global variable! Mind = blown!
This is because, as stated earlier, JS has only 2 types of scope: function (local) and global. So to solve the above mystery, you need to ask yourself: Is i in a function? No? Then it’s global.

Shadowing
If you declare a variable with the same name as a global variable in a function, the local variable always gets priority over the global one. The global one is thus inaccessible while you are inside the function. Same goes for parameter names, which are also local variables. Better avoid same names for local and global vars.

Hoisting
JavaScript fancy word #1. :-D Basically, hoisting means that all variables, no matter wherever they are declared or initialized, are always ‘hoisted’ (lifted) to the top of the script, except if they are in functions. Thus, you can do this:
foo = bar”;
var foo;

That means you can use a variable before it is even declared. Note: Only declarations are hoisted. Initializations/assignments are not. They execute on the line they were written originally.
It’s not the best practice to make extensive use of hoisting as it will eventually lead to confusing code.

No comments:

Post a Comment