SlightlyLoony
Tera Contributor
Options
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
04-04-2011
05:46 AM
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:
#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;
}
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!
1 Comment
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.