Under what circumstances is it necessary to explicitly convert a variable to a string in JavaScript?

Are there any scenarios where it is absolutely necessary to explicitly convert the variable in JavaScript to string

In the following example, this is optional:

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

I used the numerical value above, although this does not necessarily apply only to numbers.

+3
source share
5 answers

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

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

Will be s === 2

+5
source

Well, if you 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 don’t know if you ever want to do something like this.

+2
source

, :

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

, . toString, . . Object.prototype.toString.

, , , toString:

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 + ".");
+1

, . , , string , , . , :

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

With this function, you can only work with strings, because if the user inserts a number as an argument, the length property is undefined, because the Number object does not have this property, so you must specify a variable:

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

and this time it works.

+1
source

Source: https://habr.com/ru/post/1732543/


All Articles