Javascript – Print an object with alert()

During web development, sometimes we may need to print the whole Javascript object for debug purpose. You can simply dump the object to the alert box by toSource().

alert(yourObject.toSource());

 

Please note that it only works in Firefox. Try the following example.

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        myWebsite = new Object();
        myWebsite.name = 'Eureka!';
        myWebsite.url = 'https://ykyuen.wordpress.com/';

        alert(myWebsite.toSource());
      });
    </script>
  </head>
  <body>
    <p>Eureka!</p>
  </body>
<html>

 

Done =)

Reference:

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.