My favorite alternative to JavaScript’s switch statement

JavaScript By . Posted May 23, 2013

One of my least favorite parts of nearly every programming language I’ve spent much time with has been the ubiquitous switch statement. Though it does serve a useful purpose in some compiled languages, I think switch is a clunky eyesore in most code. Its structure is prone to taking root and only growing larger and more cumbersome over time.

If you’re coming to JavaScript from a background in procedural languages like C#, Java, or PHP, it’s natural to reach for the same tools, like switch, that you’re accustomed to using in those languages. However, JavaScript’s flexible object literal syntax and first-class functions offer alternatives to switch that I believe are cleaner, more extensible, and more maintainable.

So, in this post I want to show you a few ways that you can refactor a JavaScript switch statement to use this alternate technique, and improve its extensibility and maintainability in the process.
Click here to read the rest of this post »

Interesting details on IE10′s JavaScript performance tweaks

JavaScript, Short By . Updated June 13, 2012

There’s a great article on the Internet Explorer team’s MSDN blog this week, Advances in JavaScript Performance in IE10 and Windows 8. I’ve been running Windows 8 as my primary OS for several weeks, and I must say (as bizarre as it feels to type these words), IE10 is incredibly fast and fluid. It’s almost like that first time you used Chrome after using Firefox with too many add-ons. Whatever they’re doing over there, it’s working.

The entire post was interesting, and you should probably read the whole thing if you’re a serious JavaScript developer. However, one point in particular stood out to me, regarding a new approach to deferred parsing:

The JSMeter project from Microsoft Research showed that typical Web pages use only a fraction of code that they download – generally on the order of 40-50%. Intuitively, this makes sense: developers often include popular JavaScript libraries like jQuery … but only leverage a fraction of the functionality the library supports.

To optimize such scenarios, Chakra performs only the most basic syntax-only parsing of the source code. The rest of the work (building the abstract syntax tree and generating bytecode) is performed one function at a time only when the function is about to be invoked. This strategy not only helps with the responsiveness of the browser when loading Web pages, but also reduces the memory footprint.

In IE9 there was one limitation of Chakra’s deferred parsing. Functions nested inside other functions had to be parsed immediately with their enclosing functions. This restriction proved important because many JavaScript libraries employ the so called “module pattern,” in which most of the library’s code is enclosed in a large function which is immediately executed. In IE10 we removed this restriction and Chakra now defers parsing and bytecode generation of any function that is not immediately executed.

Microsoft’s focus on real-world performance enhancement in IE9 and IE10 has been an under-appreciated breath of fresh air in the browser wars. Remember when everyone was competing to improve scores on synthetic JavaScript benchmarks instead of concentrating on actual on-page performance? I don’t miss those days.

If Microsoft would address the archaic extensibility model in Internet Explorer, I’d probably be using it to type this post right now. Given replacements for the dozen-ish essential extensions I use in Chrome, I could see myself being tempted to switch back to IE after ten years of Firefox and Chrome.

The landscape today is reminiscent of how things were shaping up just before so many of us began switching from Netscape to IE5/6, way back when. Never underestimate how fiercely Microsoft can compete and innovate when an entire division of the company commits to winning.

Adding your own callbacks to existing JavaScript functions

JavaScript, jQuery By . Posted January 11, 2012

Hey Dave, is there a way to create an event handler so when .tmpl() is done it will fire a function? I’m trying to make it global, so I was hoping I could say, when ANY template gets done, do this…

The question of how to retroactively add hooks before and/or after a pre-existing JavaScript function executes is one that comes up from time to time. Whether it’s a simple method like tmpl(), a server-generated script artifact, or a function in a third-party script, sometimes it’s desirable to alter a JavaScript function without access to change the original declaration of the function.

One of the handy things about JavaScript is that you can combine its functional and dynamic aspects to make surprisingly quick work of tasks like this one. Doing so is fairly straightforward, but it involves an approach you might not consider if you’re more familiar with languages that lack JavaScript’s unique features.

In this post, I’ll briefly cover a few examples of how to “patch” existing JavaScript functions with callbacks. We’ll begin with simple examples, then address an issue that stems from applying this approach to jQuery plugins, and finish with a more elegant way to handle the problem of patching functions that accept parameters.

Click here to read the rest of this post »

Learn from my Express.js HTTP status code blunder

Express.js, JavaScript, Node.js By . Posted November 9, 2011

Screenshot of the 200 Object] HTTP status code in Firebug

If you’re like me, HTTP status code 200 Object] unknown probably doesn’t ring any bells. Of course, that’s mainly because it doesn’t exist.

So, how did I end up with the screenshot above? I’ve been running with scissors again. It was one of the more popular web frameworks for Node.js that I cut myself with this time: Express.js

Unfortunately, a malformed status code like 200 Object] will cause some browsers (including the version of Chrome I was using at the time) to refuse loading the page at all. That quickly elevated the importance of my strange status code from a trivial oddity to an annoying thorn in the side.

As it turns out, my code was running up against a documented Express feature and the remedy was simple enough.

Click here to read the rest of this post »

Resolving an iisnode “The service is unavailable” 503 error

JavaScript, Node.js By . Posted October 5, 2011

I’ve been experimenting with Tomasz Janczuk’s awesome iisnode project lately, in hopes of hosting some of my Node.js sites on IIS. Those sites are running well enough on an Ubuntu VPS currently, but the features that iisnode offers are compelling (and I have unused capacity on one of my Windows servers).

Along the way, I ran into one issue that isn’t addressed in the current iisnode documentation or examples very well. If you try to set up a standalone Node.js website in IIS you’re likely to be greeted with this error when you load it up for the first time:

iisnode 503 error screen

Remotely, you’ll see the dreaded “The service is unavailable.” error:

Those nondescript errors don’t exactly make resolving the problem very straightforward. So, I want to recap what I found to be the underlying problem in my case and a few solutions, in hopes of helping anyone else that ends up with the same issue.

Click here to read the rest of this post »

Guidance on building real-world HTML and JavaScript apps

JavaScript, Reading By . Posted September 19, 2011

Over the past several months, I’ve been participating as an adviser to an interesting Microsoft patterns & practices effort named Project Silk. I don’t publish posts here about every project I’m tangentially involved in, but I think Project Silk is worth a look if you’re building modern, JavaScript-heavy web applications.

The project itself is comprised of a complete reference application and an extensive set of documentation describing how the app works and the process behind the design decisions that the team made along the way. Think of it as the NerdDinner sample (and accompanying book chatper), but focused almost entirely on client-side development rather than the server-side MVC component.

One of the most valuable aspects of the project is that it takes aim at the almost intractable topic of building large, maintainable JavaScript applications. You can see how seriously they took that goal by the time you get to just the second paragraph of the project summary:

Click here to read the rest of this post »

Using jQuery 1.6 to find an array of an object’s keys

JavaScript, jQuery By . Posted June 8, 2011

With the confusion surrounding jQuery 1.6′s changes to .attr() and the addition of .prop(), one of my favorite new features nearly slipped under the radar. The feature I’m referring to is that $.map() now works against plain JavaScript objects in addition to arrays.

$.map() has always been a useful utility method, somewhat mimicking ECMAScript 5′s native Array.map() method. If you’ve been working with JavaScript long, you’re probably already comfortable with passing anonymous function callbacks around anyway, which makes higher order functions like map an intuitive way to write concise, expressive transformation code.

With jQuery 1.6, now you can use the same approach when working with regular JavaScript objects. There are a variety of uses for this, but I want to focus on one real-world usage in this post: extracting an array of the keys contained within a JavaScript object.

Click here to read the rest of this post »

In JavaScript, curly brace placement matters: An example

JavaScript By . Posted March 21, 2011

If you’ve been working with JavaScript very long, you probably know that you should format curly braces in JavaScript code a certain way. In fact, if you’ve watched my TekPub series, Mastering jQuery, you’ve heard me stop James and remind him that at the beginning of nearly every episode.

However, you’re less likely to have seen a clear example of why this matters or why you should care. Even when you hear advice from a trusted source, it can be difficult to heed that advice if it seems like hearsay or convention for the sake of convention.

While I was working on my recent post about extracting data objects from HTML structures, it occurred to me that some of its example code presented a great learning opportunity regarding this topic. So, I want to take advantage of that opportunity to show you a concrete example of how placing your braces on the wrong line can break your JavaScript code.

Click here to read the rest of this post »

Hear us talk about JavaScript on Hanselminutes episode 2^8

General, JavaScript By . Posted March 16, 2011

I was talking JavaScript with Scott Hanselman recently, discussing different approaches to client-side development and the complications that surround them. Part way through, he decided that we, along with Elijah Manor, should sit down and make a podcast out of it.

So, we did.

It was just a touch nerve wracking to sit down and record with no agenda, firm topic, or preparation, but Scott’s a pro and guided us smoothly through. Within an hour of him saying “let’s record a podcast,” he had pulled recording equipment and a quiet room out of thin air, and we were finished.

If you’re a regular reader here, the discussion may be below your level of expertise, but it potentially good for sharing with colleagues who aren’t yet at your level on the client-side.

You can listen to it here: <JavaScript and jQuery: Moving beyond Alert() />

Also be sure to check out Elijah’s summary of what we talked about, which includes links to most of the resources we discussed: Hanselminutes #256: JavaScript & jQuery: Moving beyond Alert()

Use jQuery to extract data from HTML lists and tables

JavaScript, jQuery, UI By . Updated March 31, 2011

A question that I’ve been seeing more frequently these days is how to extract a JavaScript object from an HTML list or table, given no data or information other than the markup. It’s not ideal to work backwards from HTML, but sometimes you just don’t have a lot of choice in the matter.

Whether you’re enhancing legacy elements that have been generated on the server-side or want to parse the output of a third-party DHTML widget, there are a variety of situations where converting HTML to raw data is a legitimate need. You may have seen iterative solutions to this problem before. However, nested looping code gets messy fast, doesn’t feel much like idiomatic jQuery, and certainly isn’t as concise as you’d probably like.

Luckily, one of JavaScript’s lesser-known utility methods and jQuery’s implementation of it can improve the situation quite a bit. In this post, I’m going to show you how to use this method, jQuery’s cross-browser solution, and how to use it to extract data objects from arbitrary HTML lists and tables.

Click here to read the rest of this post »