Serializing Objects in Javascript

It's worth noting that this post is rather old at this point. I don't use the function listed in this post anymore and haven't for a rather long time. If you are using it and it's working for you, great! But as Ron in the comments sections points out, there are a few issues with regards to strings and special characters. I recommend following the link he posts if your needs merit a very robust version of JSON serialization. I'm leaving this post up though, as I think it's helpful for folks who want to understand the general concept of recursion and serialization.

Recently, in a personal project I'm working on, I came across a need to be able to represent any Javascript object as a string. This isn't a problem since just about every object in Javascript can be represented with JSON (Javascript Object Notation). Every modern browser can parse JSON for you easily enough through eval(..), and Gecko-based browsers even have the ability to reverse the process ("uneval" if you will) and give you back a string representation of an object through a call to .toSource().

If you need this ability in any other browser though, you're gonna have to write it yourself. I needed this ability, so I wrote it (and posted it here for your enjoyment!)

Continue reading Serializing Objects in Javascript

.split(..) broken in IE

I discovered last weekend, something about IE which I had previously never known (probably because I use Firefox/Firebug to write and test most of my Javascript). It turns out that the implementation of .split(..) is broken in IE (for more complex cases). If you stick with the simpler cases when using this function, then you probably won't have ever noticed this. For example, the following works just fine:

var s = 'This-is-a-hyphen-delimited-string';
var split = s.split('-')// returns  ['This', 'is', 'a', 'hyphen', 'delimited', 'string']

The above code will work in just about every browser under the sun, including IE, but of course, it's the simplest case scenario for the .split(..) function. Many programmers will probably be aware that you're not limited to passing in a string; you can also pass in a regular expression, which IE (mostly) supports, but this is where things can start to fall apart on you (in IE anyway).

Read on to learn more.

Continue reading .split(..) broken in IE

The Javascript goto statement

There isn't one (in case you're scratching your head at the title of this post.)

Some would say this is a good thing because "goto is evil." I don't have a problem with the fact that there is no goto statement in Javascript. I do, however, have a problem with people who unconditionally think "goto is evil."

I for one, do not think goto is (always) evil. Oh it can be, don't get me wrong. But it doesn't have to be, and you shouldn't automatically assume that it is.

Donald Knuth's Structured Programming with go to Statements ... analyzes many common programming tasks and finds that in some of them GOTO is the most optimal language construct to use.

Still, as Joey Tribbiani says, "it's a moo point (like a cow's opinion; it doesn't matter)," because there is no goto statement in Javascript.

Why all this talk in a Javscript blog about something that doesn't exist in the language? Because Javascript provides an alternative. One that, if you're me, your coworkers will criticize you for using (even though it made perfect sense and actually enhanced the readability of the code!)

Read on to learn more.

Continue reading The Javascript goto statement

Word-wrap for Mozilla (take 2)

This blog entry is a follow-up to my last blog entry, Emulating CSS word-wrap for Mozilla/Firefox. In this entry, I work under the assumption that the reader has read the original post. If you haven't, I highly encourage you to do so before reading this post, as the contents of this one will be much more relevant if you do.

In my last entry, I discussed how one might achieve something similar to the CSS style rule: "word-wrap: break-word;" in Mozilla-based browsers.

The technique I used to accomplish this centered around using a Mozilla binding to automatically insert an invisible unicode hyphen between the characters of a string contained within any element whose class was set to "wordwrap." With this invisible character in place, Mozilla will happily wrap a long string whenever the element's content overflows its container.

There was a catch with my approach though. I wanted to be able to modify, not only any inner text of a "wordwrap" element, but I also needed the logic of my binding to leave in tact, any HTML that may have existed inside the given element.

The logic I ended up using was to insert the unicode character between each and every character in the element's .innerHTML (including any HTML tags). Obviously though, this would "mangle" the HTML tags thereby making them useless. So, I then added a bit more logic which utilized regular expressions plus a callback function in a .replace(..) call to "unmangle" the HTML I screwed up in the first place.

This worked, but as alert reader, Rich Birkby, kindly pointed out, there is an easier way. A way that, as it turns out, is quite simple to implement and doesn't require "mangling" any of the HTML tags within the "wordwrap" element.

Read on to learn more.

Continue reading Word-wrap for Mozilla (take 2)

Logical AND (&&) and Logical OR (||) in Javascript

Logical AND (represented as &&) and logical OR (represented as ||) are interesting critters in Javascript. You can get along for weeks, months, or even years without ever knowing the subtle nuance I'm going to discuss in this post. If your background is... well, pretty much any other language on the planet (and especially a compiled one), then chances are you've used Logical AND/OR like this:


if (x > 5 && x < 10)
{
   // x is greater than 5 and less than 10
}

But I'm guessing you probably haven't ever used it like this:


function sayHi(name)
{
   name = name || 'Whoever you are';
   alert('Hi there ' + name);
}

What's going on here? Isn't the result of a Logical AND/OR a boolean value?

Read on to learn more.

Continue reading Logical AND (&&) and Logical OR (||) in Javascript

Javascript variable scope confusion

Since Javascript has a very C/Java-like syntax, it's easy to make assumptions about the language that turn out to be rather wrong. Take variable scoping for instance. It would seem natural that a variable defined within a loop or within an if conditional, would go out of scope when that loop (or if block) came to an end:


for (var i = 0; i < 100; i++)
{
   var s = 'steve_' + i;
}
alert(s);   // steve_99 or undefined?

Run the above code snippet, and you'll get an alert that says 'steve_99'. It sort of feels like the variable s should be undefined, but it's not. I'm sure there are lots of Javascripters who already know this, but I'm also pretty sure there's also a few who've never noticed this.

Is this always the case? Do all variables created with var end up being essentially global variables? Not exactly.

Continue reading Javascript variable scope confusion

Wrapping DOM elements for easier cross-browser Javascript

One thing that has always bugged me a little about the cross-browser Javascript functions I write, is that they usually take as their first argument, the DOM element upon which the function is going to act. For example:

addEvent(myElem, evtName, myFn, false);

Here, we're forced to pass the DOM element into the function as the first argument. This works just fine, but it's a little cumbersome and doesn't read nearly as nicely as the standardized .addEventListener(..) or even the proprietary .attachEvent(..).

myElem.addEventListener(evtName, myFn, false);

Notice how in the second case, we're not passing the DOM element into the function. Rather, the function is a public member of the DOM element that we can invoke, and in my opinion, this feels a lot more natural than the first scenario.

As it turns out, mimicking this style of programming in a cross-browser fashion isn't all that hard.

Continue reading Wrapping DOM elements for easier cross-browser Javascript

Simple Javascript Inheritance

There are lots of articles out there on the web explaining how to mimic the type of inheritance many of us programmers who come from Java or C# are accustomed to. Dean Edwards, Kevin Lindsay, and Douglas Crockford all come to mind. Each has done some very impressive work in with regards to Javascript inheritance.

Each of their approaches has its own advantages and disadvantages, and each approach is (at least in my mind) a little bit confusing. Heck, Douglass Crockford even talks about kinds of inheritance I've never even heard of!

I don't hesitate for a second to admit that each of these guys is probably a more skilled Javascripter than I am, but to be perfectly honest, well... I didn't completely understand their approaches. That doesn't mean they aren't good. On the contrary, it probably only serves to illustrate how much I still have to learn.

Regardless... I'm not completely comfortable using code I don't understand, so I took a crack at my own solution -- something really simple that I did understand. Perhaps my approach may not be as robust, but it's pretty darn simple to implement (and to use), and so far I've found it to be quite effective. So enough babbling... on to the technique.

Continue reading Simple Javascript Inheritance