Free Newsletters

   All InfoWorld Newsletters
Strategic Developer | Martin Heller » Coding Tip: JavaScript isn't Java, C++, or C#, No Matter How it Looks

December 12, 2007 | Comments: (0)

Coding Tip: JavaScript isn't Java, C++, or C#, No Matter How it Looks

This memo just crossed my desk, from the CTO of one of the companies for which I consult. Caveat coder.

Looking at some of our JavaScript code it seems like the use of new Boolean() and new String() has been growing. This will get you into trouble.  For example:

var b1 = new Boolean(false);
var b2 = false;

if ( b1 ) {
   // How the heck did I get here if x is false?
   // Because Boolean objects are true in a logical context.
}
if ( b2 ) {
   // As expected, we don't execute this code.
}
var s1 = new String("");
var s2 = "";

if ( s1 ) {
   // An empty string is supposed to be logically false too!
   // But this is a String *object* so we get true.
}
if ( s2 ) {
   // We never run this code, which is correct.
}

There are almost no reasons to use the new operator to create a String, Boolean, or Number object, and plenty of reasons why you shouldn't. If you put any of those into a Session variable it can cause strange errors as well.

If you need to explicitly convert some type to another type, use its conversion operator:

var str = String(num);
var num = parseInt(string);

Posted by Martin Heller on December 12, 2007 12:04 PM


RATE THIS ARTICLE:





 

  •  
  • COMMENTS




Don't forget that if string is not a number, parseInt(string) returns NaN, which you can detect with isNaN(num).

Posted by: Doug in Seattle at December 21, 2007 09:33 AM

Technology White Papers

 

InfoWorld Technology Marketplace

» Technology White Papers Library

Technology White Papers by Topic

Technology White Papers E-mail Alert

Find out when the latest white paper is available:
 
 
» BUY A LINK NOW

Sponsored Technology Links