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

How to convert argument to a string in JavaScript?

I would really appreciate it if someone could explain to me how to convert an argument to a string?

function descendingOrder(n){
  var str = n.toString();
  return str;
}
document.write(descendingOrder(321));

3 Answers

function descendingOrder(n){
 var str = n.toString();
 return str
}
 document.write(descendingOrder(321));

This below, returns a string for me and the one above :). No need for str I don't believe.

function descendingOrder(n){
return n.toString();
}
 console.log(descendingOrder(321));

I also double checked the method is working correctly:

function desOrder(n){
return n.toString();
}
let test = desOrder(321);
console.log(typeof test);

ale8k How comes on document.write it comes up as 321 rather that "321"? Thanks

It's returning it to the test and then console.log is converting it's value into a presentation format.

let test = 'test';
test;

^ shows it with "" as we are directly calling test

function desOrder(n){
return n.toString();
}
let test = desOrder(321);
console.log(typeof test);
test; // this is calling the test variable

this is it all together ^, console.log is where you're getting confused :P It's very much like when you return objects, they don't look like an object from console.log but they are XD or Arrays with .join(), doesn't look like an array but it is :P

Thanks, appreciate it.