JavaScript: Numbers to Strings

Javascript is pretty casual about strings and numbers. Because javascript is an untyped language, it’s easy to get used doing things like:

var aString = "kb" + 63; // results in string "kb63"
Instead of choking, javascript will treat the number 63 as a string and concatenate them together for you.

Sometimes, you really need a string or a number. For example, you might have a database key that you want to use as an array index:

var dbKey = 546735289; // some surrogate key out of the database.
var dbObject = {
   name: "Kenneth",
   age: "old",
   likes: "beer"
};
var theArray = new Array();
theArray[dbKey] = dbObject;

But now, theArray.length is 546735290 - one more than the index. Javascript arrays are sparse, so this might not cause any memory problems since memory should only be allocated for the single array element at 546735289. However, if you loop through the array using a for loop theArray.length times, performing some expensive operation inside the loop - such as a complex DOM manipulation - you might get into trouble.

In this case, you’d be better off using a named property instead of a numeric array index. To convert a number to a string:

    // use the toString method
    dbKey.toString

    // use the String() constructor
    String(dbKey)

    // concatenate a number with empty string. Crude and ugly
    dbKey + ""

What if you want to go the other way, from a string to a number? The cheap and easy way is to do some math on the string:

    var myString = "1000";
    var myNumber = myString * 1

Don’t try and use the + operator:

    // won't work. javascript thinks concatenate
    var myString = "1000";
    var myNumber = myString + 0; // results in the string 10000

Leave a Reply