Hoisting in JavaScript

One of the key concept of every programming language is the Scope. In JavaScript, variable and function scoping is a little bit different and so cool! you can have multiple var (variable) in a function, All of them run well if you declare at the top of the function. (althought you wont get any kind of error if you declare at the end of the function) For example:

  1. console.log(variable);    // undefined
  2. Var variable="something";

Now, notice about the following code:

  1. var x = "something ";
  2. console.log(x); // something
  3. if (true) {
  4.         var x = "another thing";
  5.         console.log(x); // another thing
  6. }
  7. console.log(x); // another thing.

As you can see, the value of x changed during the scope and finally the changed value returned. So in JavaScript, scope affects the outer of its own. Now if you change the above code as a function scope, the output will be different:

  1. var x = "something ";
  2. console.log(x); // something
  3. Function Test() {
  4.         var x = "another thing";
  5.         console.log(x); // another thing
  6. };
  7. Test();
  8. console.log(x); // something 

The value of x(I mean "another thing) is in the scope of Test function only. so functions create a new scope in JavaScript and block is not a scope just like C#, C++, …

There is another interesting feature in JavaScript, which is about variable declaration. Take this:

  1.  (function () {
  2.         var a = 1;
  3.         alert(a + " and " + b );
  4.         var b = 2;
  5.     })();

as I mentioned It’s not a syntax or compile error, but if you run this function it will alert "a and undefined". in these cases you should just hoist the variable, Hoisting is the act of moving the declarations to the top of the function. And you should move them on top! the JavaScript looks ahead to find all the variable declarations and hoist them to the top of the function. Variables in JavaScript are hoisted, it means Rather than being available after their declaration, they might actually be available beforehand. So if you hoist the above function's variables, it would be like this:

  1. (function () {
  2.         var a = 1;
  3.         var b = 2;
  4.         alert(a + " and " + b );
  5.   })();

Rather than variable hoisting, we have function hoisting too, for example:

  1. foo();  // TypeError , undefined
  2. foo2(); // defined
  3.  
  4. Var foo=function(){
  5.        //operation
  6. };
  7.  
  8. Foo2(){
  9. // operation
  10. };

We called the function (I mean foo2()) before declaration. Notice that foo() is not a function at all in line 1 and function definition hoisting only occurs for function declarations.

 


Tags: JavaScript


comments powered by Disqus