2

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.

1
  • what would you expect to see in the string if null or undefined was passed in, for example. Commented Jul 15, 2010 at 19:05

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

How about

var str = '' + someVar;

2 Comments

@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.
+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 :)
1

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"

Comments

1

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

Comments

0

How about ... ?

var theVarAsString = "" + oldVar;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.