Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  181] [ 3]  / answers: 1 / hits: 29700  / 13 Years ago, thu, april 21, 2011, 12:00:00

What are the use cases for doing new String(already a string)?



What's the whole point of it?


More From » string

 Answers
27

There's very little practical use for String objects as created by new String(foo). The only advantage a String object has over a primitive string value is that as an object it can store properties:



var str = foo;
str.prop = bar;
alert(str.prop); // undefined

var str = new String(foo);
str.prop = bar;
alert(str.prop); // bar


If you're unsure of what values can be passed to your code then I would suggest you have larger problems in your project. No native JavaScript object, major library or DOM method that returns a string will return a String object rather than a string value. However, if you want to be absolutely sure you have a string value rather than a String object, you can convert it as follows:



var str = new String(foo);
str = + str;


If the value you're checking could be any object, your options are as follows:




  1. Don't worry about String objects and just use typeof. This would be my recommendation.



    typeof str == string.


  2. Use instanceof as well as typeof. This usually works but has the disadvantage of returning a false negative for a String object created in another window.



    typeof str == string || str instanceof String


  3. Use duck typing. Check for the existence of one or more String-specific methods, such as substring() or toLowerCase(). This is clearly imprecise, since it will return a false positive for an object that happens to have a method with the name you're checking, but it will be good enough in most cases.



    typeof str == string || typeof str.substring == function



[#92618] Tuesday, April 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlyn

Total Points: 421
Total Questions: 73
Total Answers: 100

Location: South Georgia
Member since Sat, Jul 25, 2020
4 Years ago
;