JavaScript: Datatype Coercion...


Our young friend at right is skeptical that we ever need to force JavaScript to use any particular datatype, but actually the need arises often. If you write any JavaScript at all, you're probably using implicit datatype coercion already, though you may not know it. But what this post is all about is using explicit datatype coercion. “Why?”, you ask. Consider this code:

var y = x + 3;

If 'x' contains a number, then 'y' will contain the arithmetic sum you'd expect. But if 'x' had a string representation of a number (e.g., '045'), then 'y' will contain a string with the '3' concatenated (e.g., '0453') instead of the arithmetic sum you wanted. This code will fix it, by explicit coercion:

var y = x - 0 + 3;

By asking JavaScript to subtract zero, we force (coerce!) JavaScript to convert 'x' to a number – exactly what we want. Subtracting zero from a string is just a ‘trick’ to force the coercion to a number. Here are some more:

From To Use this
string boolean !!x
string number x - 0
string object new String(x)
boolean string '' + x
boolean number x - 0
boolean object new Boolean(x)
number string '' + x
number boolean !!x
number object new Number(x)
object string x.toString()
object boolean !!x -or- !!x.toString()
object number (!!x) - 0 -or- x.toString() - 0

There's one more similar issue that isn't really coercion, but often comes up in similar circumstances. Suppose you have a variable 'x' that has a number, and you want to get just the integer part of it. In other words, if 'x' is 3.4, you want to get 3, and if 'x' is -56.787, you want to get -56. Here's how you can do it:

(x < 0) ? Math.ceil(x) : Math.floor(x);

Now go forth and coerce!


Comments

Very cool!

Very cool!

__________________

Matt Gaide, Technical Consultant | ServiceNow | www.service-now.com
Transform IT
ServiceNow

ServiceNow Employee

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.