The difference between != and =!

Posted on December 31st, 2008 in JavaScript | No Comments »

I was helping a js novice troubleshoot some of her code today and found the culprit to be a typo in one of her conditional statements:

// var USERID = 12345;
if (USERID =! null){
     // code
}

Her expression was always resolving to true because she had inverted her != (”not-null”) check which was actually assigning her variable to the return of a statement evaluation. Her mistake would be clearer to understand formatted as such:

// var USERID = 12345;
if (USERID = !null){
     // code
}

Since the inverse of false, null, and NaN is true her conditional statement (also an assignment) would always return true.

Which lead me to thinking, the not operator is a great way to write succinct code. In the right context, using the not operator in the right side of an assignment isn’t a bad idea.

Improve your jQuery - 25 excellent tips

Posted on December 16th, 2008 in JavaScript, jQuery | No Comments »


Here’s a nice write-up by Jon Hobbs-Smith at tvidesign.com detailing 25 tips on using jQuery as well as regular JavaScript advice. Most of these tips probably aren’t anything new for the advanced jQuery user (Jon considers himself intermediate, I think that’s modest), however I love lists like this because there’s a treasure trove worth of experience being shared. Altruism at it’s best!

I plan on writing more entries on my own tips and tricks with JavaScript and jQuery as well as my methods of debugging in various browsers, compression techniques, etc., but in the meantime, I’ll just comment on Jon’s list:

2. Use a [jQuery] cheat sheet

I think Visual jQuery is all you need. And now that there’s live search and clickable examples it’s even better.

3. Combine all your scripts and minify them

Dead Edward’s packer is awesome for minifying, but before I do that, I like to run my code through jSlint to make sure it’s all valid. I ignore line-break errors as I don’t agree in many cases that it’s an issue.

Additionally, when I work on large JS codebases with a lot of other people who may not code as strictly as I do, I like to use JSmin on the minimal setting (cut-and-paste version here). The compression benefit is only slightly less and it preserves single linefeeds preventing JS errors where people forgot to end their statements with a semicolon. It also makes the code easier to read and debug in a production enviornment—great for the times you want the benefits of minification without the side effect of obfuscation.

5. Keep selection operations to a minimum by caching

I just wanted to comment in Ron’s example where he used:

var myList = $('.myList');

First, if I ever reference a jQuery collection in my scripts, I like to append the dollar sign character to the beginning of the variable name to signify that it is, in fact, a jQuery collection:

var $myList = $('.myList');

It’s a lot more helpful when you access that variable further down the road and don’t have to question whether it’s a jQuery wrapped set, an actual HTML element, or something else.

Secondly, whether you’re using a JS lib or not, I would never search for an HTML collection by class name alone; What the JavaScript engine is doing in the background is looping through every single element on the page which is very intensive. It would be better to find the closest parent container first or search by specific tag name(s):

Good:

var $myList = $('ul.myList'); //added benefit of knowing the type of element you'll
// receive

Better:

var $myList = $('#closest_parent_id .myList'); // searching the children of a parent
// container instead of all the elements on the page

Best:

var $myList = $('#closest_parent_id ul.myList'); // combination of both above

19. Use noconflict to rename the jquery object when using other frameworks
22. How to check if an element exists[…]

As I’ve probably mentioned before, I always like to use noConflict() in all my projects. I move jQuery to the $j namespace and save $ for a shorthand reference to document.getElementById - I think it’s what most js developers expect and if($('myDiv)) is a lot simpler to write out than if($('#myDiv).length !== 0) or even if($('#myDiv).length).

Thanks for the link Bryan!

Blogging from South Korea

Posted on November 9th, 2008 in Personal | 1 Comment »

I’m on my vacation now in South Korea, and in keeping related to tech, I have a few things to blog about:

  1. PC bangs (rooms) are all over the place, almost as much as nara bangs (karoake rooms) and the general cost is 1000 won ($1) for two hours of awesomely fast internet!
  2. Both of the PC bangs I’ve been to so far have IE6 installed as the default browser with nothing else (although they’re all relatively new machines). :(((((
  3. On the upside, it looks like you can install anything you want (I installed Firefox) but I’m guessing the computer gets reimaged somehow once you log out. I was also allowed to hook my Macbook up.
  4. Atleast in the area I’m in (Inchon), wireless networks seem to be less prevalent here than in the US, especially the wide open or free ones (and thusly I’m at a PC bang.)
  5. Instead of relying on expensive phonecards and such to call the States, I use my Skype number (about $30 for 6 months). It gives me unlimited calling to the US and Canada and my own NYC number friends can call so they don’t get charged for long distance. Even though I’m not even close to NYC it still calls them like I it did when I am in my office. Win/win.
  6. I decided to step up from my old 4-year-old Sony Cybershot and bought a Nikon D90 DSLR before the trip. It works just like my old Nikon N80 (non-digital SLR) and I’ve been enjoying the crisp 12mp images and 1080p video capabilites. I want to make a DVD when I get back in two weeks.
  7. And lastly, Starcraft is just as fun as I remembered it. :(

Charging your iPhone on the go

Posted on October 29th, 2008 in iPhone | No Comments »

The Kensington Mini Battery Pack for iPod and iPhone

So I’m planning a 2 week trip to Korea, and I know during the course of my trip I’ll probably be watching lots of video on my iphone, potentially siphoning off internet for my MacBook, and reading my Google Reader when I can. All of that would lead to the quick demise of my iPhone’s battery life - with no AC outlet in sight. To remedy this I’ve been planning to get an external battery pack - something like the Kensington’s Mini Battery Pack ($50) [inset left].

The other day, however, I was at the local Duane Reade (popular NYC pharmacy chain) and came across this in the $10 discount bin [inset right].

Energizer Energi To Go Portable Power for iPod

It’s called the Energizer Energi To Go ($10?) and what is basically does is recharge your iPod via two double-A batteries. Although the packaging only advertises charging iPods, I took the chance and bought it considering all the connectors are the same. Sure enough it works great! I’ve only tested it out twice but I dig it. Here’s the pros and cons:

Energizer Energi Pros

  • It’s cheap. Judging from the condition of the packaging this things been around for awhile, and I’m pretty sure I’m not the only guy that’s never heard of it. I mean, Energizer, making an iPod accessory? It even comes with a free pair of batteries.
  • It’s easy to charge. You can get a small box of double-A’s anywhere and in most countries I assume. I could go camping for days and still be able to make calls and get online.
  • It’s small. Easy to slip in a jacket pocket if you know you’ll be needing it. It folds compactly when you’re not using it and also serves as a stand when you are. Here’s an unoptimized WMV movie (6MB) from their site showing the folding action. Additionally the device has a coin-operated screw area so that you can expand the dock to fit larger or smaller devices.

Energizer Energi Cons

  • It’s a little wasteful. And probably worse for the environment. A set of batteries can charge an iPhone about 1.2 times before being emptied.
  • Long charge time. Takes a good couple of hours to charge.
  • Dock can be a little fickle. I’m not sure whether it only happens when the batteries or low but sometimes my iPhone beeps / vibrates constantly as if it’s constantly getting unplugged and replugged.

Overall, I definitely think the pros outweigh the cons, especially for my case where I’m not going to be using it much. I’ve got an iPhone dock ready at home and work so the only time I need it would be when I’m away from both places for longer than a day. The charging time isn’t so bad either since I can charge and use it at the same time (I only wish it could somehow dock horizontally for MovieTime™.)

This marks the end of my review, so if you have ten dollars burning a whole in your pocket go to your local Duane Reade store and try to pick one up!

String.toCharCode

Posted on October 27th, 2008 in JavaScript | 7 Comments »

I noticed that JavaScript has a String.fromCharCode for decoding a sequence of numbers to Unicode values but no String.toCharCode for doing the reverse. So here’s my rendition:

String.prototype.toCharCode = function(){
    var r = '', string = this.split('');
    for (var i in string){
        r += String.charCodeAt(string[i]) + ',';
    }
    return r.substr(0,r.length - 1);
}
 
'bob'.toCharCode();
// returns "98,111,98"

Update: version from my good friend Takashi and link to his blog on why it’s more efficient:

String.prototype.toCharCode = function(){
    var str = this.split(''), len = str.length, work = new Array(len);
    for (var i = 0; i < len; ++i){
        work[i] = String.charCodeAt(str[i]);
    }
    return work.join(',');
}
 
'bob'.toCharCode();
// returns "98,111,98"