Tech Junkie Blog: JavaScript Object Deep Dive: toString() and toLocaleString() Methods

Friday, December 22, 2017

JavaScript Object Deep Dive: toString() and toLocaleString() Methods

Every JavaScript object has a toString() and a toLocaleString() method defined with it.  It is a string representation of the object. 

For example if we define a date object like the following:

 var date = new Date();

and we output the console.log(date.toString()) method without any extra code we would get the current date and time automatically







By default the toString() method outputs the long form of the date and time.  If we want to output a format that is tied to the current locale of the browser.  We can call the toLocaleString() instead. Like the following:

console.log(date.toLocaleString())

and the output will be like the following:







The toString() method works for arrays as well.  Let's say we have an array of countries like the example below:

var countries = new Array("U.S.A","Canada","China");

We can output the toString() method to the console with the following code:

console.log(coutnries.toString());

and you would see the following output.






However, the toLocaleString() method will give you the same result because the method does not perform any special locale functions for you.  It only works for the date.  In order to out the locale representation for the array you need to write your own custom toLocaleString() method for the array.





No comments:

Post a Comment