Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Object Deep Dive: toString() and toLocaleString() Methods

Sunday, May 30, 2021

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



JavaScript console display of date.toString()






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:

JavaScript console display of date.toLocaleString()






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.

JavaScript console display of Array.toString()





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.



1 comment:

Search This Blog