Categories
Jquery

Best way to safely convert object to string in Javascript

Know the ways to converst javascipt objects to string. Object to string conversion method example.

Many time we need to convert JavaScript object into string. To do this there are several ways. To do is safely here is two js function to convert object to string. You can use any of them.

function makeString(object) {
      if (object == null) return \'\';
      return \'\' + object;
    };

//Test function
var number =100;
document.write(\'<p> number to string\'+makeString(number)+\'</p>\');
var d = new Date();
document.write(\'<p> number to string\'+makeString(d)+\'</p>\');
//below line is equal to above
document.write(\'<p> number to string\'+d+\'</p>\');

var cars = ["Saab", "Volvo", "BMW"];
document.write(\'<p> number to string\'+makeString(cars)+\'</p>\');

Above makeString function will change object to string safely.

Here is another version of above function and both has same results.

function makeString(object) {
      if (object == null) return \'\';
      return String(object);
    };
js example