0

I was just wondering, in most of my projects I have been able to use:

  • the String() function,
  • the toString() method and
  • the JSON.stringify() method (I don't really use this),

to convert data in JavaScript to string without much difference and I was wondering what exactly the difference was between using each of them.

Thanks for reading through, I'll really appreciate your answer.

Lapys
  • 936
  • 2
  • 11
  • 27
  • 3
    [here](https://stackoverflow.com/questions/15834172/whats-the-difference-in-using-tostring-compared-to-json-stringify) & [here](https://stackoverflow.com/questions/3945202/whats-the-difference-between-stringvalue-vs-value-tostring).. – palaѕн Oct 06 '17 at 16:53
  • 1
    Wait, you didn't see a difference between `String` and `JSON.stringify`? Try again on a value that is not a number or `null`. – Bergi Oct 06 '17 at 16:55
  • https://github.com/airbnb/javascript#coercion--strings – Justin Niessner Oct 06 '17 at 16:56

2 Answers2

1

This is the explicit use of the native constructor function that creates and returns a string object when used with the new operator or the string value only when used without new.

This invokes the object's toString() method which returns the string representation of the object, which, if not overridden, usually is something like [object Object], which indicates the instance and the type. Custom objects often will override this inherited method to be able to display the best string representation of that particular object.

This takes an object and converts it into the JSON data format. Without using an optional "replacer" function, all properties that store functions will be stripped out of the string. This is generally used when an object is packaged to hold data and then that data is to be sent over HTTP to another location.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0
  • String() is a global string constructor, that accepts anything htat should be converted to string ad returns primitive string. Under the hood this calls Object.prototype.toString()(https://www.ecma-international.org/ecma-262/5.1/#sec-15.5.1.1)
  • Object.prototype.toString() is a method that return string representation of an object: the value of type String that is the result of concatenating the three Strings "[object ", class, and "]", where class is internal property of object. This function can be overriden
  • JSON.stringify() method converts a JavaScript value to a JSON string; Boolean, Number, and String objects are converted to the primitive values during the process
Andrzej Smyk
  • 1,684
  • 11
  • 21