Mike Morearty
28 Jul 2008

ActionScript’s different ways to convert an object to a string

ActionScript has several different ways to convert an object to a string, and figuring out which one to use can be confusing. This post compares them, and tries to give you a deeper understanding of what is going on.

String(myobj)

This is often the best choice. If you don’t remember anything else from this post, just remember that String(myobj) is the “safest” way to convert an object to a string.

Although String is a type, String() is also a function. It isn’t a constructor – it is a regular function. Its behavior is to take whatever argument you passed it, and convert it to a String.

This function will pretty much always succeed without throwing an exception. The only case where it will throw an exception is the unlikely case that myobj.toString() gets called and that function throws an exception.

The behavior of String() is formally defined by section 9.8 of the ECMAScript spec. (Note, this is confusing: When the ECMAScript spec refers to “ToString” or “[[ToString]]”, they are not talking about the toString() function – they are talking about the formal definition of what ECMAScript should do if it needs to convert any object to a string.)

The main thing to remember is that it will always return a string – e.g. if myobj is null, String(myobj) will return the string "null", and if myobj is undefined, String(myobj) will return the string "undefined". If myobj is a user-defined type, String() will end up calling its toString() function.

"" + myobj (or myobj + "")

This is functionally equivalent to String(myobj). Because of the rules of ECMAScript’s + operator, "" + myobj will result in String(myobj) being performed on the second argument, and then being concatenated with the empty string. Concatenation with the empty string is very efficient in the Flash player, so don’t worry about that.

myobj.toString()

This is fine for most cases – it will work on numbers, booleans, user-defined objects, strings, etc. – but if myobj is null or undefined, this will throw an exception. Explicitly saying myobj.toString() means you explicitly want to call the toString() member function of myobj, but if myobj is null or undefined, then of course it can’t have any member functions.

myobj as String

You won’t use this very often. The "as" operator means, “If the object is already an instance of the specified type, then cast it to the specified type and return it; otherwise, return null.” So myobj as String will return myobj cast to a String if myobj is already a String, and will return null if myobj is any other type. In most cases this is not the behavior you are looking for.

myobj.toXMLString()

Don’t forget that if myobj is of type XML or XMLList, then String(myobj) and myobj.toString() will work, but may or may not give the result you wanted; you may want myobj.toXMLString() instead. See part 5 of Common E4X Pitfalls.

comments powered by Disqus