empty string + null = "null"?

encodeuricomponent, javascript

Solution

The overloaded `+` operator attempts to convert both operands to a common type before performing its operation. If either operand is a string, it converts both operands to a string and then performs string concatenation.

See the ecmascript definition for the behavior of the `+` operator:

If Type(lprim) is String or Type(rprim) is String, then Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

Problem

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.

Original source

Related problems