SlightlyLoony
Tera Contributor

find_real_file.pngOur 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:
#customers {
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
width:100%;
border-collapse:collapse;
}
#customers td, #customers th {
font-size:1em;
border:1px solid #914D21;
padding:3px 7px 2px 7px;
}
#customers th {
font-size:1.1em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#914D21;
color:#ffffff;
}
#customers tr.alt td {
color:#000000;
background-color:#EAF2D3;
}














FromToUse this
stringboolean!!x
stringnumberx - 0
stringobjectnew String(x)
booleanstring'' + x
booleannumberx - 0
booleanobjectnew Boolean(x)
numberstring'' + x
numberboolean!!x
numberobjectnew Number(x)
objectstringx.toString()
objectboolean!!x -or- !!x.toString()
objectnumber(!!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!

1 Comment