0

Of the many methods to convert to a string, I am confused between:

var foo = new String(val);

vs

var foo = String(val);

When to use one over the other ?

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • 2
    Primitive vs object. `new String` is not used. `String` to cast a string yes. Or `''` for anything else. – elclanrs Feb 28 '15 at 00:19
  • @elclanrs could you expand a bit ? – JavaDeveloper Feb 28 '15 at 00:21
  • 1
    `typeof new String('foo') == 'object'` and `typeof String('foo') == 'string'` – elclanrs Feb 28 '15 at 00:22
  • @Oriol question is not a duplicate, someone new to javascript does not know that String('a') is not an object, – JavaDeveloper Feb 28 '15 at 00:23
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Distinction_between_string_primitives_and_String_objects – Malk Feb 28 '15 at 00:24
  • More info here http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.2 – elclanrs Feb 28 '15 at 00:24
  • @JavaDeveloper Maybe yes, but the difference between `String` and `new String` is the same as the difference between a primitive [String value](http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.16) and a [String object](http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.18), so in that sense they are duplicates. Maybe [Why does (“foo” === new String(“foo”)) evaluate to false in JavaScript?](http://stackoverflow.com/q/10951906/1529630) would have been better. – Oriol Feb 28 '15 at 00:33

0 Answers0