views:

70

answers:

5

Are there any scenarios where it is absolutely necessary to perform an explicit cast of a variable in JavaScript to a String

In the following example it is not necessary:

var n=1;
var s = "Hello" + n;  
var s = "Hello"+String(n); //not necessary

I've used a numeric value above, although this need not apply only to numerics.

+2  A: 

Yes, if you want "11" instead of 2.

var n = 1;    
var s = n + n;

Will be s === 2

Doug D
+1  A: 

Well if your want to display two numbers side by side...

var a=5, b = 10;

alert( a+b ); // yields 15
alert( String(a) + String(b) ); //yields '510'

but i do not know if you would ever want to do something like this..

Gaby
+1  A: 

I would say it is necessary in this situation:

var n = 20; 
var m = 10;
var s = String(n) + String(m); // "2010" String
Daniel Vassallo
+1  A: 

It depends on the type of object you are working with. The basic objects already have a useful toString method that turns them into strings. But custom objects don’t. They will inherit the method from Object.prototype.toString.

So whenever you have a custom object that should return a useful string when converted to string, define a toString method:

function Human(name) {
    this.name = name.toString();
    this.toString = function() {
        return this.name;
    };
    return this;
}
var alice = new Human("Alice");
alert("Hi, I’m " + alice + ".");
Gumbo
+1  A: 

Usually a variable is converted to string when you want to use string methods on that variable. I think that the most useful case is when you must use a string method inside a function and you don't know what type of variable the user passes into the function. For example if you want to calculate the number of characters in a variable:

function length(s)
{
    return s.length;
}

With this function you can only work with strings because if the user inserts a number as argument the length property is undefined, because the Number object doesn't have that property, so you must cast the variable:

function length(s)
{
     s=s+"";
     return s.length;
}

and this time it works.

mck89