NetBen Ramblings about JavaScript and frontend development.

16Jan/10Off

Mea culpa, it was obvious.

Kind guys in prototype IRC channel pointed me to this article http://yura.thinkweb2.com/named-function-expressions/ which explains what's happening.
qFox from fronteers IRC also kicked me in the groins for not knowing the difference between expressions and declarations.

Basically, declarations are compiled before anything else inside a scopeblock, causing the "functions float to top" feature.

1
2
3
4
test(); // alerts "Hello world!"
function test() { // declaration
   alert("Hello world");
}

This ofcourse creates ambiguous code and should not be done if you want your code to be clear and appearant.
Instead declare functions as part of an expression by assigning them to variables or properties.

1
2
3
4
5
test(); // alerts undefined
var test = function test() { // expression
   alert("Hello world");
}
test(); // alerts "Hello world!"

The fact that it seems to work in FireFox is because they foolproofed it and now I get it, I feel they shouldn't have.
Though the declaration spec creates ambiguity, it's the spec, it does exactly as ordered and a browser should not fix developer mistakes and incompetence.
(Yeh, I was incompetent myself for not knowing this! I admit it! sigh)

I read a lot of books, written a lot of JS code and read oogles of JS articles on the web and this little piece of (in hindsight) common wealth information always eluded me. So leaving my rather newbish blog post up so other devs who run into this, will have yet another article to explain what they're encountering.

Filed under: JavaScript No Comments
16Jan/10Off

If/else + functions = madness

My code style might not be perfect, but the following code should be pretty straight forward in what to expect right?

if(true) {
   function test() {
      alert("SUCCESS!");
   }
} else {
   function test() {
      alert("FAIL!");
   }
}
test();
// alerts "SUCCESS!" in FireFox (3.5.7)
// alerts "FAIL!" in IE8, Opera 9.62, (win) Safari 4.0.4
// need to install and test this in google's Chrome still!

Whats going on here???!

I first encountered this "feature" in Safari and thought it was a local incident, though to my suprise, I reproduced it in other browsers as well!

Function literals float to the top of the scopeblock, however functions inside a failed clause, should be ignored by the interperter.
Am I missing the reason why so many browser vendors implemented it this way?
Is FireFox/Mozilla actually the odd duck here? And if so, for the love of god, why?
Is this a recent development? A discrepancy introduced by engines competing eachother over speed?

Also kinda weird that after years of JavaScript, I encounter this now...
Or is this something I never encountered before untill I started bloating my code for better readability, structuring and reducing if/else expressions?

Sure, we can mitigate this easily by changing our coding style and never declare functions through the literal notation, assigning anonymous functions to variables.

if(true) {
   var test = function() {
      alert("SUCCESS!");
   }
} else {
   var test = function() {
      alert("FAIL!");
   }
}
test();
// alerts "SUCCESS!" everywhere =/

But that's just plain daft... using function literals is pretty straightforward and everyone will trip constantly over this discrepancy when trying to write clean/clear code.
Now I have to explain to Java developers learning JS that they should avoid using function literal declarations...

Will investigate further.

Filed under: JavaScript No Comments
10Jan/10Off

What is JavaScript, really? Part 1, the runtime.

I am currently in the process of preparing to teach some Java/backend developers JavaScript and intend to try my damn hardest to teach them the potential JavaScript can bring to any environment. Unfortunatly that entails going into low level JavaScript to first explain the difference between an expressive dynamic script language and a rigid compile language. We frontend developers use JavaScript daily and never really sit back and think about what it is that we're actually working with and thus the language persists of having a reputation of being arcane, illogical and certainly not better then a good compiled application. That's just plain wrong, but how do we explain that!

Don't compare!

Comparing JavaScript with any compile language is a farce though, it's apples and bananas, in fact, comparing JavaScript with other dynamic languages is also equally ridiculous as most other script language still compile into bytecode or simply isn't muteable at runtime. No, what really sets JavaScript apart is not so much the language, but it's marriage with the runtime interperter (engine). Frontend developers complain about various runtime engines (usually IE's) and never really stand still to marvel at the brilliance of those engines, wether they support JavaScript entirely or not.

JavaScript ROCKS!

I mean, here we have an environment where we can plug in our programs and on runtime adapt the program entirely changing it's behaviour and logic on the fly! It goes far beyond the realm of write and run. A lot of credit for this goes to the engine, however the standards on which JavaScript is based creates a perfect marriage of language and runtime. For example, without muteable objects, applications that make use of extreme dynamics would be bloated hogging too much memory, take away lambdas and all throw-away-execute-once methods would be persisted on objects, again hogging more memory. And then there are closures, lovely, brilliant closures, without closures lamda's wouldn't even be half as effective as you would always be forced to create methods instead of functions to adress other objects.

JavaScript SUCKS!

All this expressive power and potential however comes at a cost. Obviously not compiling to bytecode and interpeting commands at runtime sacrifices performance, the algorithms you can and should perform are restricted to relative simplicity limiting the things you can do with JavaScript and it's runtime. Is that bad? No, not really, we go from a process taking nano seconds to miliseconds and whilst huge computations (3D or even 2D rendering for example) remain out of grasp for JavaScript, it's still more then good enough for most mundane tasks. For example, you simply do not need immense processing power for 3D and 2D x,y,z calculations whilst leaving the rendering to native or more specialist API's, which coincidentally can be added to the JavaScript runtime.

So how does it compare?

Ok, time to compare apples and bananas as I feel it's needed to fully understand. Languages that compile to bytecode and pretty much have everything predefined inside a container, are overkill and too rigid for mundane tasks. You can get pretty far with compiled programs, but that means having a huge initial code base for simple functionality, forcing you to use predefined components in places where flexibility is required. Components are adapted to support more functionality and flexibility and become unwieldy and ambiguous to work with. So basically, with compile languages it only makes sense to make ok looking applications, otherwise it would simply cost too much time to develop.

Whereas in JavaScript, this becomes as easy as pie (if you learn it properly) since you are not restricted by the conventions most compile languages impose on a developer and whilst all this expressive power creates at first glance, ambiguous confusing code, it's really not that hard to maintain once you can let go of all the conventions and restrictions other languages put on you. So JavaScript liberates you in the right places.

In conclusion

Whilst JavaScript is currently being ported to the backend and desktop, it's my opinion that this is a mistake if you can't make it talk or integhate to/with compiled programs. I see JavaScript more as a language that tells other program API's what to do, preprocessing and reformating user defined options before inserting the data or commands into an compiled application. This is where the dynamic runtime shines and where the compiled runtime becomes restrictive. In browsers JavaScript is the language developers use to push other application API's around like the DOM, Flash, and even the browser itself. It can do the same with serverside API's whilst integrating directly with the clientside API's and with some imagination, JavaScript can be used as a logic operator between multiple platforms simplifying interfaces to bare essentials.

I will have a hard time teaching JavaScript properly to java/backend developers... Part 1 is about showing them it's not *another* programming language, but a rich addition to *any* programming language. Time to kick them out of their sandbox!

Filed under: JavaScript No Comments
4Jan/10Off

JSoo goes to the fridge

Whilst this blog was accomodating sound space for crickets, JSoo changed a lot since my last post. However a lot has happened since my last post as well, most importantly, YUI3 and google's closure got open sourced as well as ECMAScript edition 5 being published!!! JSoo was a good learning ground (especially to identify low level problems), however it's original purpose is redundant leading me to put JSoo itself into the proverbial fridge.

Disclaimer: All findings are based on first impressions superimposed on my knowledge and expectations. Please try it out yourself and form your own opinion, beware false prophets!

YUI3

YUI3 is just brilliant, in many ways it killed JSoo, but in my honest opinion, it's a happy death ;) YUI3 is a great allround library and for me "allround" entails a collection of abstractions to work with the DOM, HTTP and browser environments, mechanism(s) to modularize your code and means to "progressively enhance" your websites and applications.  There's still room for immediate improvements though, for example while it's great Yahoo provides their own modules, using your own modules is more work then using YUI's modules simply because you have to repeat and resolve dependencies at "deploy time". I mean, you first need to construct your webapplication(s) sorting dependencies and then you need to sort dependencies again when you want to deploy your code into your website/app.

For me the logic place to resolve and define dependencies would be at module level, not implementation level, but I do understand why Yahoo chose for this, when you fire up a module chain, you want to parallel load all dependencies. Though in my opinion, using initializers might be an awnser to keep dependency resolutions in one place, in fact, I will be releasing a mini lib soon that does just that, based on some of JSoo's old code.

Google Closure

It's brilliant as well, but a monstrousity. Closure in it's entirety is not intended for your average run of the mill website, but for hardcore web applications. The API and documentation feels like it's written by hard core programmers for hard core developers, containing classes and tools that in my opinion should've been abstracted away from plain site. Now all it does is confuse people and scare developers. Luckily some people realize that and Micheal Bolin (formerly of Google) created Closure Lite, so if you're interrested in Google Closure, first delve into Closure Lite to first identify the good abstractions from the low level abstractions (I can't call them bad ;) ).

The compiler is interresting, but like compiling in GWT, it assumes everything is good at compile time and thats not really what asynchronous-on-demand-progressive-enhancement development is about. It forces a strictness where dynamic freedom is required, it feels like going backwards instead of forwards using ideoms that work great for other languages ignoring the fact this is a whole new playground we're all dealing with. In all fairness, thats my beef with all "compilers", they still put a lot of architectural decisions into the developers hands and frontend architecture is a mess where a good cleaning is needed.

The templating system of Google Closure is a fail. The ES side is nice, we frontend developers are used to silly names, but no selfrespecting Java developer will import the dependency "com.google.template.soy.tofu.SoyToFu" and use it. The mindset of most Java developers is that if it sounds like crap, it's probably crap. What's in a name? A lot actually, clarity is quite important in Java. Shame really, besides the name, the templating system is rather funky ;)

Verdict

Google Closure Tools is brilliant, but it's old school, I feel it will become redundant very soon. Google NEEDED to release a JS library to compete with Yahoo as GWT simply adresses a too small a market and right now they are behind. Google can gain up on Yahoo if they invest more into the compiler so it compiles to an on-demand-asynchronous-progressive-enhancement application. Right now, Yahoo is imo. the winner out of the two, so for big ES projects, use YUI3 (or Dojo).

How did Dojo get in here!?

Filed under: JavaScript, JSoo No Comments