JavaScript – It’s Up Your Sleeve
This afternoon, JavaScript left me scratching my head due to an interesting fun little fact that I didn’t know. For full effect, picture the scene.
I’m having a perfectly reasonable day, improved slightly by the amount of Tina Turner I had been listening to. I’m working on an application that captures interesting conversations from Twitter, with the intention of seeding it with a great discussion between Uncle Bob and Dan North from last week.
The said conversation is withering away in Twitter’s archive and I’m hoping to complete this application swiftly before parts of the conversation become inaccessible to the API. I’m actually in the process of finishing the last bit that allows you to remove tweets from the final conversation.
In order to remove individual tweets, the full list is sent down to the client in an AJAX response. Each tweet is rendered in a <div> and has a new attribute that holds the tweet ID.
Let’s emulate the situation to demonstrate the problem:
<script type="text/javascript">
var data = { id: 487592080484679444 };
function addAttribute() {
$('#element').attr('id', data.id);
}
</script>
<div id="element"></div>
<a href="javascript:addAttribute()">Add Attribute</a>
Starting from the top, we have an object called data which has a field called id. The value of id is the numeric ID of a tweet, which we’ll be adding to the <div>. The addAttribute method finds the <div> and sets the id attribute to the value from the object.
Let’s run it and see what happens. Before we click the link, the DOM looks like:

As expected, we have our <div> and its id is still set to ‘element’. Now let’s click the link and cause the addAttribute to run. Here’s the DOM afterwards:

And there we go, our id is now set. But wait, what the hell – take another look at the value of the attribute and compare it to the value in the object. In pure JavaScript magic, it seems our original id of 487592080484679444 has been transformed into 487592080484679400.
While being wholly entertaining, and the very good trick not withstanding, I’d like to keep my hair for a few more years. After looking into the problem, it turns out that I was (until now) blissfully unaware that:
All numbers in Javascript are 64bit (8 bytes) floating point numbers…
Integers are considered reliable (numbers without a period or exponent notation) to 15 digits (9e15). Floating point numbers are considered only as reliable as possible and no more!
(http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference)
Ah, 15 digits – that’s how it’s done.
Good one JavaScript, but not so impressive now that I know your dirty secret. Looks like it’s strings for this one.


2 Comments
leave a commentTrackbacks and Pingbacks