2

Is there a difference? Will string 2 inherit different object prototypes?

var s1 = 1234 + '';
var s2 = String(1234);

//s1.someNewFunc();   error?
//s2.someNewFunc();

Thanks

wayofthefuture
  • 8,339
  • 7
  • 36
  • 53

4 Answers4

4
var s1 = 1234 + '';

Creates a string literal. This is a javascript language primitive.

var s2 = String(1234);

The String() function also returns a primitive string literal. s2 will have the same members as s1 because they are both the same type.

However

var s3 = new String("1234");

Will create an object of type String rather than a primitive string literal. This does have different members and is of type object.

bhspencer
  • 13,086
  • 5
  • 35
  • 44
  • damn... now i'm more confused as to which one to use! – wayofthefuture Jul 24 '15 at 22:20
  • Don't worry about it. There isn't much use for new String() http://stackoverflow.com/questions/5750656/whats-the-point-of-new-stringx-in-javascript I would just use the string literal and be done. – bhspencer Jul 24 '15 at 22:22
  • 1
    @Dude2TheN I recommend just using literals for primitive types. When creating your own object I would use `new myObject(...)` – Spencer Wieczorek Jul 24 '15 at 22:22
2

Same thing!

var s1 = 1234 + '';
var s2 = String(1234);

typeof s1   //string
typeof s2   //string
Alon
  • 2,919
  • 6
  • 27
  • 47
1

Both will behave the same way.

Also, there is a nice explanation about string primitives vs. objects here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

Distinction between string primitives and String objects

[...] String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. [...]

pdenes
  • 782
  • 6
  • 9
0

Javascript allows you to treat primitive values as though they were objects. It does so by doing an on-the-fly coercion of the primitive to an object. That's why, even though primitives have no properties, something like this is perfectly fine:

"abcde".substr(1,3); //bcd
true.valueOf(); //true
chiliNUT
  • 18,989
  • 14
  • 66
  • 106