Home > Back-end >  Is there any difference between using toString() method than just simply calling it?
Is there any difference between using toString() method than just simply calling it?

Time:12-06

I've been testing some examples but I don't see any difference

const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

and

const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

but it just gives me the same results..

CodePudding user response:

You can rely on the implicit call of toString() here.

JavaScript calls the toString method to convert an object to a primitive value. You rarely need to invoke the toString method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

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

CodePudding user response:

No, there is no difference between using the toString() method than just simply calling it. The toString() method will convert any array, object, or number into a string representation. It has no effect on strings.

The toString() method is a built-in JavaScript method that can be used to convert any array, object, or number into a string representation. When used on a string, the toString() method does not change the string in any way. It simply returns the same string that was passed in.

The toString() method can be used to convert objects and numbers into strings, which is useful when printing them out or when combining them with strings.

EDIT To further elaborate:

By using the toString() method in the example provided by OP:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

The elements of the array are separated by commas and the result is a single string. When the array is directly assigned to the innerHTML property of an element, it is also converted into a string. Therefore, both lines of code in the example produce the same result.

  • Related