How to convert JavaScript objects to primitive data types manually?


Primitive data types are nothing but a string, number, boolean, etc. To convert objects to primitive data types, javascript has provided some methods such as toString(), valueOf(), etc. Using these methods javascript objects can be easily converted to primitive data types.

Example-1

In the following example, normal arrays were converted into primitive data type 'string' and the result is displayed in the output.

Live Demo

<html>
<body>
<script>
   var arr = [1, 2, 3];
   document.write(arr.toString() + "</br>");
   var arr1 = ['Hello','Hi','Glad','Pleasure'];
   document.write(arr1.toString() + "</br>");
</script>
</body>
</html>

Output

1,2,3
Hello,Hi,Glad,Pleasure


Example-2

In the following example, date object were converted into primitive data type 'number' and the result is displayed in the output.

Live Demo

<html>
<body>
<script>
   var d = new Date(2018, 5, 24);
   document.write(d.toDateString() + "<br>");
   document.write(d.valueOf());
</script>
</body>
</html>

Output

Sun Jun 24 2018
1529778600000
raja
Published on 01-Aug-2019 16:15:52
Advertisements