Not a long time ago, for me the Java Script is for the uninitiated or for people who are not supposed to be programmers. Spoiled offspring of well groomed Java. Well, that opinion has changed forever and it didn’t take a long time.
Variable Scoping is one of those.
This kind of ‘hoisting’ is applicable for function declarations as well.
Speaking of functions, Yes, there are no classes. And I would use the cliche - ‘Function is a first class citizen in Java Script’. What is meant by that is you can pass a function to another function as you would pass any other variable.
Isn’t it poweful?
But what about objects? Can I ‘encapsulate’ things and use? Yes you can. First, there are object literals.
And “Wait for it” you can create objects out of a function.
Function itself acts as a constructor in this case.
You can just access any of the properties like this -
Or even like this -
But wait a minute, there are no privates? is everything public?
But nothing is impossible with Java Script. You can have your privates too. Enter closure.
The ‘print’ function above forms a ‘closure’ for ‘mySecretNum’, and it stays private. This feature is powerful especially with ‘Ajax’. But that topic is for some other time.
It is just amazing the kind of things you can do with what you thought was a little smelly scripting language.
But with great power comes greater responsibility, and if you are not responsible, you will soon end up with unmanageable spaghetti code like this.
And that is a recipe for disaster. Something that makes one so averse to read, understand or use.
First there was AJAX, then GMail happened, JQuery came along, Node was born. There were Firefox and Chrome.
Ain’t it worth giving a try?
Go, Do it.
(Note: This was a write-up I penned for a news letter of the organization I work for. Unfortunately the news letter never came out)