Because using .toString() for null vars doesn't work, and I can't be checking each and every one of these in my particular application.
I know this is a stupidly simple problem with an answer that literally must be staring me in the face right now.
The non-concatenation route is to use the String() constructor:
var str = new String(myVar); // returns string object
var str = String(myVar); // returns string value
Of course, var str = "" + myVar; is shorter and easier. Be aware that all the methods here will transform a variable with a value of null into "null". If you want to get around that, you can use || to set a default when a variable's value is "falsey" like null:
var str = myVar || "";
Just so long as you know that 0 and false would also result in "" here.
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String
How about
var str = '' + someVar;
String(myVar), however, an edge-case might be when a form value is itself "null". These are the kind of bugs that can make life hell 1 month down the line :)String(null) returns "null", which may cause problems if a form field's value is itself null. How about a simple wrapper function instead?
function toString(v) {
if(v == null || v == undefined) {
return "";
}
return String(v);
}
Only null, undefined, and empty strings should return the empty string. All other falsy values including the integer 0 will return something else. Some tests,
> toString(null)
""
> toString(undefined)
""
> toString(false)
"false"
> toString(0)
"0"
> toString(NaN)
"NaN"
> toString("")
""
nullorundefinedwas passed in, for example.