Skip to content

jQuery .data() Auto-casting Changes

A bit of background on this one before I dive into a rant:

Just over three years ago, I wrote an answer on Stack Overflow regarding jQuery.fn.data() vs jQuery.fn.attr(). My answer, which really focuses on the utility of the .data() function, has essentially become the canonical answer for various niche questions and minor bugs relating to .data() and .attr(). I'm quite surprised and delighted by the popularity, as it's my highest up-voted answer.


What I just found out this evening disappoints me.

In jQuery 1.8 rc 1, the .data() method was changed so that auto-casting numbers no longer auto-casts numbers if their representations would change from the cast. The simplified way of understanding this is as follows:

If the value in the attribute is 1000, it will be auto-cast to 1000 as a number. If the value in the attribute is 1e3, it will not be auto-cast, and have a value of "1e3" as a string. This is because, even though 1e3 is proper scientific notation for the value of 1000, the representation would change to 1000.

I feel as though this violates the principle of least astonishment. It's already reasonably well established that when accessing [data-*] attribute values, the values will be cast to their appropriate JS types. If you need to preserve the formatting of a value, the proper way to access the value is via .attr(), not .data(). This change only introduces inconsistency.