JavaScript JavaScript Arrays Loop Through Arrays Search for a Value in an Array

Kylie Soderblom
Kylie Soderblom
3,377 Points

What is the functional difference between Array.prototype.join() and Array.prototype.toString() ?

inStock.join(", ") does make a comma and a space between array elements while inStock.toString(", ") ignores the space and only has a comma between array elements.

Is there any other reason to use join instead of toString?

Reggie Williams
seal-mask
.a{fill-rule:evenodd;}techdegree
Reggie Williams
Treehouse Teacher

Hey Kylie Soderblom the main difference is that the join method takes a seperator parameter while toString doesn't take any. Without the parameter given, their behavior is identical

1 Answer

Hi Kylie!

The biggest difference is that toString() just builds a string from an array with elements separated by only a single comma (and no spaces). In other words, there are no options.

With join(), you can specify ANY separator of your choice.

Keep in mind, however, join() and toString() would give the same result (when join is called without an argument).

So this:

var cars = ["Saab", "Volvo", "BMW"];
console.log( cars.join("---") );

Would log the string:

 Saab---Volvo---BMW

to the console.

More info:

https://www.includehelp.com/code-snippets/join-vs-toString-methods-in-javascript.aspx

I hope that helps.

Stay safe and happy coding!