I came across an odd occurrence today while troubleshooting a rogue AJAX request in our application. We send data back to the server, using jQuery.param
to build the request string.
In one scenario, the object fed to the param function had a null option, so it looked something like this:
var myData = {
x : 1,
y : null
};
var params = jQuery.param(myData);
This code is actually buried in a backbone collection, but the principle is the same.
Now, I was completely shocked when the parameter, when received by the server, for the variable y
was the literal string "null"
, rather than being null
.
After some digging, I found that encodeURIComponent(null)
returns the string "null"
and more interestingly '' + null
yields "null"
as well. This was tested on Chrome 23, as well as Firefox 11.
The object ultimately being sent to the jQuery.param
function gets built from arguments to a function, and null is a completely valid value for the parameter. I got around it by just building the object with y : param || ''
, but I'm curious as to the apparent wrongness of the native JS function, as well as why '' + null = "null"
, since they are generally regarded as two different concepts.