views:

62

answers:

5

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.

+2  A: 

How about

var str = '' + someVar;
Pointy
Seems slightly hackish...? Meh, it'll work.
Hamster
@Hamster Sure it's hackish, so stick it in a function to make it cleaner. Then you can make it smarter if you end up with new kinds of variables to deal with.
Ken Redler
+1 - short and simple, works just like `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 :)
Anurag
A: 

How about ... ?

var theVarAsString = "" + oldVar;

rlb.usa
+4  A: 

The non-concatenation route is to use the String() constructor:

var str = new String(myVar);

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

Andy E
+1  A: 

What about

var str = (variable || "");
//or
(variable || "").toString();

Of course you'll get this for false, undefined and so on, too, but it will be an empty string and not "null"

Simen Echholt
A: 

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("")
""
Anurag