Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Arrays Methods: Part 2

rafael perez
rafael perez
4,269 Points

why we keep using the toString function?

Can somebody please explain me why we keep using the toString ?(we saw that in a previus video but i didn't get it).

1 Answer

Hi rafael,

Sometimes its needed to have a toString() to display the correct values.

Consider this block of code:

var myArray = [0,1,2,3]; 
console.log('My array at start: ', myArray); ////Returns : Array [ 1, 2, 3]

//Adding element to array
myArray.push(4);
// INCORRECT VALUE
console.log('My array after push without toString: ', myArray); //Returns Array [ 0, 1, 2, 3 ]
// CORRECT VALUE
console.log('My array after push with toString: ', myArray.toString()); "0,1,2,3,4"

//Remove element from array
myArray.pop();
// CORRECT
console.log('My array after pop without toString: ', myArray); //Returns Array [ 0, 1, 2, 3 ]
// CORRECT
console.log('My array after pop with toString: ', myArray.toString()); //Returns "0,1,2,3"

Hope that helps

rafael perez
rafael perez
4,269 Points

Hi Michael, thanks for your answer, i appreciate it. I understand that i just have to use it but still i think it's weird, like kind a bug in js. Not very logic for me, but anyway...

Ive been doing some more research on this subject. Its mainly a browser issue. It works fine in chorme and firefox but I still have this bug with firefox developer edition. In most cases it should be fine but to be safe you can use toString.

rafael perez
rafael perez
4,269 Points

Thanks again Michael :) Ok, so it's more a problem with the browser than a js bug, still weird but more logic ;) As you said, i'll keep using toString.