Tuesday, August 18, 2015

Functional JavaScript: Scope and Hoisting

JavaScript: putting the fun in functional since 1995!


With so much function going down it's hardly surprising that JavaScript is a functional language.

But what do we mean by that?

Well a function is kinda like an independent mini-program within a program. And so any variables you create inside a function only have meaning inside that function. When the function finishes, the variables disappear - as in they will not be carried over into subsequent functions. This is actually a really good thing as a JavaScript program could have hundreds or thousands of variables and would become very difficult to keep track of if they all carried over into the other functions. It means we can re-use variable names within other functions and it won't cause problems elsewhere. These variables are known as local variables.

There's also another type of variable known as a global variable. Unsurprisingly these global variables are defined at the main script level and are available to use inside each function.

The concept of local vs global variables is referred to as scope.



Slightly confusingly, in JavaScript a variable can used before it's been declared. This is because JavaScript moves all declarations to the top of the current function - this is called hoisting.


Hoisting is often an overlooked area of JavaScript, and just because something can be done doesn't mean it necessarily should. And, indeed, the example above will return an error. This is because only the declaration (var y), not the initialization (= 7) is hoisted to the top. So you could put var y lower in the script, but you can't initialize it with, in this case = 7, and expect a result.

And really, for anyone reading your code surely it would be better to declare your variables before calling them? And since this is how JavaScript interprets the code (after it has 'hoisted' the variable) then it's always a better rule to follow!

4 comments:

  1. Could you clarify what you mean by 'When the function finishes, the variables disappear.'?

    ReplyDelete
  2. Absolutely. And I just have done with a tiny update - When the function finishes, the variables disappear - as in they will not be carried over into subsequent functions.

    Does that work?

    ReplyDelete
  3. I guess I would say that it's not so much that they disappear (that only happens when the garbage collector comes to take them away) just that they cannot be accessed by any 'higher up' functions.

    ReplyDelete
  4. Fair enough, that makes sense to clarify.

    ReplyDelete