RSS

JavaScript: Required Reading

My colleagues often ask me how they can improve at JavaScript. I usually start by replying with the obvious (and correct) answer of “you need to write more of it”. However, since supplying only that answer would be a total dick move, I have also been casually gathering and pruning a list of [IMHO] the most important and/or confusing concepts in JavaScript.

The following is the short-list of JavaScript concepts that I feel one must understand before they can [eventually] achieve mastery of the JavaScript language.

Read the rest of this entry »

 
4 Comments

Posted by on 2013-03-11 in JavaScript

 

JavaScript: Noteworthy Tools & Libraries

Last Updated: 2013-03-19

I am the co-organizer of the Twin Cities JavaScript users group known as JavaScriptMN.  At one of our recent meetups (2012-05-31), we were set to have 30 minutes of discussion and/or lightning talks on the theme of “tools and libraries that you couldn’t live without”.  While the goal of the theme was to point out the most valuable tools and libraries available, our main speaker for the night was missing in action and so we continued discussing tools and libraries for the entire duration of the meetup.  I’ve put all the suggestions together into a composite list and categorized them all, though the order of the categories themselves is definitely a bit askew.

Please note that this is not intended to be a list of the best tools/libraries in each category but rather providing a small set of those available.  The reason behind this is that many of them are still actively in development (the coverage tools are a good example), and so I don’t want to only list the single option that I feel is best at this point in time as it may be eclipsed by one of its listed competitors (or something totally new!) in the near future.

My intent is to keep this blog post up-to-date as time marches on, so be sure to keep a link to it handy (or just to my main blog page, as I’ve made this post “sticky” as well).  Now, on to the list!

Read the rest of this entry »

 

The Node.js Revolution, or: How I Learned to Stop Worrying and Love the Node

Hello, Node!

As a self-admitted JavaScript lover, I was neither surprised nor disgusted (as some JS “haters” were) when I first heard about Node.js bringing server-side JavaScript to the masses!  Running on top of Google Chrome’s V8 JavaScript engine clearly gave it an advantage not shared by its predecessors like Microsoft’s JScript (atop the Windows Script Host) and Mozilla’s Rhino.

That said, I investigated Node.js early in its life and the stability I was seeking from it in order to utilize it for enterprise-level production-ready server-side JavaScript (for a purpose very similar to the one outlined by David Padbury on his blog) was simply not there yet, especially on the Windows platform.

And so I shelved looking at Node for about 9 months.

Nine Months Later…

Perhaps Node.js was pregnant unbeknownst to me when I left her… because when I returned to my abandoned fling 9 months later, I found that she had given birth to a great many new and wonderful things!  Weird analogies aside, what I hadn’t noticed happening due to my absence from the scene was that many strong JavaScript developers in the community had rallied around Node.js.  Eager for a reprieve from the web-based world where JavaScript was bound by browser incompatibilities and inconsistencies, they happily brought their skills and ideas to the beautifully browserless world of Node.js and began to form an incredibly rich and thriving ecosystem around it.

While existing tools like PhantomJS and Esprima became even more useful than before, many new tools — Mocha, BusterJS, node-cover, and coveraje, to name just a few — came into existence to improve upon existing but stale tools (e.g. JsUnit/QUnit/Jasmine, JSCoverage).  More recently, Grunt, a promising new build tool for front-end projects was released, again built atop Node.js.

Also, having a completely server-side environment also drove home the importance of JavaScript’s lack for modules, and so CommonJS and Asynchonous Module Definition (AMD) were both solidified as a result.

What Does It All Mean?

The Good:

  • I think the new libraries and tools created as a result of the Node.js revolution are amazingly useful — but better yet, even though most of them were created for use with Node.js, they still apply (or have been retrofitted to apply) to the traditional browser-bound world of JavaScript as well.
  • Having CommonJS and AMD for module specs is great!  In fact, I actually prefer AMD over ECMAScript Harmony’s proposal for native module support.
  • Node.js has rallied the JavaScript community to band together again as professionals doing cool stuff as a collective group.

The Bad (or Regrettable):

  • Unfortunately, it seems that many of the JavaScript world’s best and brightest have almost completely abandoned the frustrating traditional browser-bound world of JavaScript in favor of the unshackled browserless world of Node.js.  While this is good for them as individuals and for the Node.js community, I can’t help feeling that it is also a loss for those of us still fighting the never-ending battle with client-side JavaScript in a world of incompatible, inconsistent browsers.  That said, again, we have still seen some residual benefits in the form of new libraries and tools that apply to both worlds.

So what do you think about the Node.js Revolution?

 

State of the Art?

As you can see, it’s been a while since I’ve posted anything about JavaScript but my world has changed dramatically in that period that I’ve been away.  For a quick glimpse of what I’m working on and what’s to come, here are the technologies and libraries that I’ve been working with more recently.

Actively using:

  • JavaScript in general (duh)
  • jQuery (for core awesome-sauce, e.g. DOM manipulation, AJAX network requests, Promises/Deferreds)
  • RequireJS (for Asynchronous Module Definition, async script loading, and dependency management)
  • Backbone.js (for MV* structuring)
  • Underscore.js (for client-side templating) — Not a huge fan, really only using it because it’s integrated with Backbone.js)
  • QUnit [and its alternate upcoming site] (for JavaScript unit testing)
  • Jetty (for an on-demand HTTP server to execute HTTP-bound JavaScript unit tests during CI)
  • JsMockito (for mocking) — I’ve heard praise that Sinon.js is better. Any feedback?
  • JSCoverage (for code coverage) — Isn’t there something better than this yet? Can someone explain how I can use NodeCover to gather the same/better metrics?
  • PhantomJS (for headless execution of unit tests during CI) — Rocks so hard!
  • JSDoc Toolkit (for documentation generation from comments)
  • Ant plus Ant Contrib (for main build) — Old, I know, but struggling to find better alternatives. Do you know of any?
  • Rhino (for running the r.js optimizer via Ant)
  • YUI Compressor (for JS and CSS minification) — Employer is understandably hesitant to switch to a minifier that rewrites our code (e.g. UglifyJS, Google Closure Compiler) on a large, existing JavaScript web app. Do you have any info/stats to help me push them past this?
  • JetBrains WebStorm (for IDE on Windows)
  • SASS (for “more awesomer” CSS)
  • IE Dev Tools, Firebug, & Chrome Dev Tools (for debugging)
Investigating:
  • Node.js (as potential replacement of Ant as a build tool, as potential replacement of Jetty as an on-demand HTTP server, and other experimental purposes)
  • TestSwarm (for cross-browser unit testing during CI)
    • Beautiful reporting grid output
    • Requires pre-attachment of browsers
    • Definitely alpha software, though
  • Selenium Grid (for cross-browser unit testing during CI)
    • Much more robust than TestSwarm
    • Can launch its own browsers
    • Crappy reporting output

Evaluated and didn’t see any immediate use for:

  • CoffeeScript (for “more awesomer” JavaScript?) — Seemed more like a learning curve for our large employee base of non-Rubyists/non-Pythonistas
  • Dart (laughably heavy, plus yucky old Java syntax)
  • Jasmine / Pavlov (for BDD testing)
  • JsUnit (used to use it for unit testing before QUnit)
  • JavaScriptMVC (too heavy-handed compared to Backbone)
  • Knockout (preferred Backbone)

Help me out!

Do you know of tools I should utilize for use cases not mentioned (e.g. tool to detect changes to JS/CSS and auto-refresh my browsers)?  Do you know of better alternatives for a given use case mentioned above?  If so, I’d love to hear about it!  Please leave a [constructive] comment.

 

What the hell, IE….

So last night I was bitten by a very unexpected behavior in the IE JavaScript engine (IE7, specifically, but I would suspect it’s present in all the other versions).

Background
I have a function that iterates through the characters in a string trying to align them with those from another string. I was doing this with a for loop from 0 through “length – 1″ and then pulling out the pertinent character from the string using the indexer, e.g.

for (var c = 0; c < myString.length; c++) {
    alert("char at index " + c + " was: " + myString[c]);
}

Problem
This seemed to work fine in all of my initial tests and works like a charm in Firefox.  However, when I flipped back to IE7 to run my JSUnit tests there as well, I saw about 7 errors in my results.  Turns out it was an error from when the string was a single character, e.g. “x”.  From an object perspective, JavaScript still knows it’s a string because all of the string methods are available.  However, use of the indexer, e.g. myString[c], caused it to blow up, saying that myString[c] was undefined.

My assumption here is that, in IE, the indexer syntax actually tries to retrieve the index from its internal data structure (i.e. char[]) rather than its JS representation (i.e. String).  However, it seems that when the string is only one character long, its internal representation is just a plain ole char rather than a char array.  Very odd!

Solution/Workaround
Any which way, this was easily worked around by using the string methods instead:

for (var c = 0; c &lt; myString.length; c++) {
    alert("char at index " + c + " was: " + myString.substring(c, c + 1));
}
 
Comments Off

Posted by on 2009-11-26 in Browsers, IE7, JavaScript, jWalker, Open Source

 

Tags:

TreeWalker: The ultimate DOM traversal provider

The W3C’s DOM Level 2 calls for the existence of a JavaScript class by the name of TreeWalker, which all DOM Level 2-compliant browsers (amongst the modern ones, this is all but the IE browsers) have successfully provided. But wouldn’t it be nice to have a TreeWalker available in IE too? This is the question that was raised at work during a story with very intense JavaScript requirements. And so, I set out to build a cross-browser TreeWalker (obviously leveraging the native TreeWalker when available). I blew through a number of methods easily (parentNode(), firstChild(), lastChild(), previousSibling(), nextSibling()), but had to call it quits for the night when I got to previousNode() and nextNode()… much too complicated to think about at the late hour. I did get some confirmation by looking at Mozile’s (Mozilla In-Line Editor) TreeWalker JS (http://mozile.mozdev.org/0.8/src/dom/TreeWalker.js).

Looks like they also have some JS files in the same folder (http://mozile.mozdev.org/0.8/src/dom/InternetExplorerRange.js and http://mozile.mozdev.org/0.8/src/dom/InternetExplorerSelection.js) to give IE ranges/selections the capabilities of a W3C Range and the Mozilla Selection object, respectively, that I may have to peek at to see if I can refactor any of the RangeInformation class I put together to wrap ranges in a mostly cross-browser fashion.

Along with the Selection library I’ve recently created, I’d love to publish a copy of the TreeWalker to the open source world. We’ll see….

Update:
Upon second inspection the next day, it turned out that parentNode, firstChild, lastChild, nextSibling, previousSibling were all actually harder methods than I had given them credit for, and nextNode and previousNode were actually the easy ones. The complications come from the whole “logical view” as defined in the W3C spec for DOM Traversal (DOM level 2) that features the TreeWalker.

 
Comments Off

Posted by on 2009-10-29 in JavaScript, jWalker, Open Source

 

Unraveling the pitfalls of JS inheritance

So with the aid of a colleague and the good ole O’Reilly “JavaScript: The Definitive Guide, Fourth Edition” book, I pinned down a previously unexplainable problem with the JS inheritance work I was doing.  Basically, I was trying to create a base widget that more complex widgets would inherit from — pretty standard inheritance idea.  Here’s the basic code concept to illustrate….

MyNs.BaseWidget = function() {
    this.parentElement = null;
    this.childWidgets = [];
};
MyNs.BaseWidget.prototype.AddChildWidget = function(childWidget) {
    this.childWidgets.push(childWidget);
};
MyNs.BaseWidget.prototype.Draw = function() {
    this.DrawSelf();

    for (var c = 0; c > this.childWidgets.length; c++) {
        var childWidget = this.childWidgets[c];
        childWidget.Draw();
    }
};

MyNs.ComplexWidget = function() {
    // Some new properties of no consequence
};
// The next two lines chain prototypal inheritance
MyNs.ComplexWidget.prototype = new MyNs.BaseWidget();
MyNs.ComplexWidget.prototype.constructor = MyNs.ComplexWidget;

// Create objects!
var myChildWidget = new MyNs.ComplexWidget();
myChildWidget.parentElement = document.getElementById("childDiv");

var myMainWidget = new MyNs.ComplexWidget();
myMainWidget.parentElement = document.getElementById("parentDiv");
myMainWidget.AddChildWidget(myChildWidget);
myMainWidget.Draw();

Now what happened was by far the most confusing thing I’ve ever encountered: the “parentElement” property on each object was set correctly; however, the “childWidgets” property on myChildWidget (which should’ve been of length 0) was actually identical to myMainWidget’s “childWidgets” property (which had a length of 1).  While confusing, the real problem here is that it spawned an infinitely recursive loop when invoking the Draw method as there was always one child widget to draw regardless of the context of “this”.  I noodled on that problem for a few idle days before my colleague and I finally stumbled upon the reasoning in our quest to solve the problem today (yay for pair programming as needed and the fact that I actually asked him to look at it with me).  The scoop follows!

The prototypal inheritance model of JavaScript with regard to inherited properties operates under the following basic rules:

  1. Rule #1: If the derived class never modifies the inherited property, any “read-only” references to that property will actually use the property from the base class instead.
  2. Rule #2: If the derived class directly modifies the inherited property, it makes a copy of the base class’s property for itself and masks its ties to the base class’s property.  However, if the derived class’s copy of the property were to be deleted (destroyed from memory), trying to access said property will again link to the base class’s property.
  3. Rule #3: If the inherited property is never modified (so the derived class still points to the base class’s property) and it is INDIRECTLY modified (e.g. childWidgets.push({});), the call to grab the property itself is seen as a read-only reference and therefore pulls the base class’s property and then updates that.

Now knowing this, such a folly can easily be solved with some code changes as highlighted in the following….

MyNs.BaseWidget = function() {
    this.parentElement = null;
    this.childWidgets = null; // was: = [];
};
MyNs.BaseWidget.prototype.AddChildWidget = function(childWidget) {
    if (this.childWidgets == null) {
        this.childWidgets = [];
    }
    this.childWidgets.push(childWidget);
};
MyNs.BaseWidget.prototype.Draw = function() {
    this.DrawSelf();

    if (this.childWidgets != null) {
        for (var c = 0; c > this.childWidgets.length; c++) {
            var childWidget = this.childWidgets[c];
            childWidget.Draw();
        }
    }
};

MyNs.ComplexWidget = function() {
    // Some new properties of no consequence
};
// The next two lines chain prototypal inheritance
MyNs.ComplexWidget.prototype = new MyNs.BaseWidget();
MyNs.ComplexWidget.prototype.constructor = MyNs.ComplexWidget;

// Create objects!
var myChildWidget = new MyNs.ComplexWidget();
myChildWidget.parentElement = document.getElementById("childDiv");

var myMainWidget = new MyNs.ComplexWidget();
myMainWidget.parentElement = document.getElementById("parentDiv");
myMainWidget.AddChildWidget(myChildWidget);
myMainWidget.Draw();

Here we see that by not having the property declared in the base class’s constructor (except to null, which is not its intended value), but rather instantiating it in the first call to the “AddChildWidget” method (which will be invoked an instance of the derived class), we have fallen into Rule #2 rather than Rule #3 as before: now the new derived instance is creating an instance of this array for itself.  Success!

Final word: it should be noted that, although my example here focuses on hierarchical chaining (“composite” design pattern), the problem described here would show itself just as easily when there are two derived instance objects on the page at the same time even if they had no direct relation to each other.  The only thing that makes it more evident in a hierarchical chaining example like this one is the unfortunate introduction of an infinitely recursive loop.  ;)

 
Comments Off

Posted by on 2009-09-24 in Inheritance, JavaScript

 
 
Follow

Get every new post delivered to your Inbox.

Join 131 other followers