0

I've looked around but can't find a definitive answer.. I'm new to Javascript so hoping to find an answer in simple terms

I'm learning about toString / valueOf, which are described as essentially doing the same thing

Can someone please explain why these need to be used at all? E.g. in the below code, why do you need valueOf / toString if document.write(array); will do the same thing?

var array= ["James Jones", "123 Street", 500.20];

document.write(array.toString());
AddB
  • 47
  • 4
  • Possible duplicate of [valueOf() vs. toString() in Javascript](https://stackoverflow.com/questions/2485632/valueof-vs-tostring-in-javascript) – MathKimRobin Aug 01 '18 at 19:56
  • You shouldnt have to specifically call `toString()` on the array to use that method. the `document.write` will do it for you. Im a little confused by what exactly your asking. – ug_ Aug 01 '18 at 20:05

3 Answers3

2

Array.prototype.valueOf will return the same as just the Array (an Object). toString will convert the Array to a String, which can be written to the document.

toString will convert other Object types to a String as well.

var array = [1, 2, 3];
console.log("Value of:",array.valueOf());
console.log("Array: ", array);
console.log("toString: ", array.toString());
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

This is because the write() cannot use an array as an input for the method. In order to use the method, the array must first be converted to a string.

Generally speaking, methods like valueOf an toString are used to convert the value of one object type to the value of another object type. For example, valueOf is used when converting a string to an integer, such as converting "23" to 23. On the contrary, toString would act in an opposite way, converting 23 into "23".

Hope this helps!

alakh125
  • 41
  • 9
0

Can someone please explain why these need to be used at all?

You don't have to use them in most cases. In a lot of cases, js will call them for you (implicitly), but that they are defined as methods allows you to customize them:

 alert({ toString() { return "whats going on?"; } });
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151