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

Why does .toString() method return undefined?

Trying out some code in console.

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var newFruits = fruits.toString();
document.getElementById("demo").innerHTML = newFruits;
</script>

in the console I type in:

typeof newFruits; //returns "undefined"

My thought is that fruits.toString() would have stored the string in newFruits, so the type should be a string. Why does it return "undefined"

Believe that .toString() should only be utilized when you want to convert a number into a string. If you're looking to make your array fruits into a full string that you'd like to apply to the #demo element, recommend using the .join() method and applying a (" ") within the join parameter. Such like,

<script>
var newFruits = fruits.join(" ");
document.getElementById("demo").innerHTML = newFruits;
</script>

3 Answers

I suspect a typo? Write all the JS in the console to check the value. Your code is fine and I was able to test to make sure.

Boom thanks Michael! Learn something new each day :)

Thanks, I would normally use join. But I'm trying to learn array methods, and .toString() is an array method according to Mozilla Developer Network. arr.toString() is supposed to return a string but I'm getting undefined.

Steven Parker
Steven Parker
243,318 Points

Are you still getting undefined?

I agree with Michael, you probably had a typo. Your code works for me.

You might try this variant, which also worked for me:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var newFruits = fruits.toString();
console.log("newFruits has type '" + typeof newFruits + "', and contains: " + newFruits);