Wednesday, January 16, 2013

JavaScript: console.log() - Best Practice

JavaScript developers, must be well aware of the console.log() function to log messages to the console window.

Today, I share my experience to write a wrapper function for console.log().

Simple Code 1: Ignore log message if the console object is missing


<script type="text/javascript" language="javascript">
    window.console = window.console || { log: function (d) {} };
    
    /* write your JavaScript code below this line */
    console.log("Message: Testing Console.log");

</script>


Simple Code 2: Modified to show log message as alert if the console object is missing and the global variable for debug is set to true. You can turn it off when you publish to production.


<script type="text/javascript" language="javascript">

    var debug = true;

    window.console = window.console || { log: function (d) 
        {if(debug){alert("Sorry! Logger not available on this 
            browser. \n\n" + d);} } };


    /* write your JavaScript code below this line */
    console.log("Message: Testing Console.log");

</script>


Simple Code 3: Same as above but with JQuery.


<script type="text/javascript" language="javascript">

    var debug = true;

    $(function(){
      window.console = window.console || { log: function (d) 
        {if(debug){alert("Sorry! Logger not available on this 
            browser. \n\n" + d);} } };
    });


    /* write your JavaScript code below this line */
    console.log("Message: Testing Console.log");

</script>



More Info:

This is a best practice to avoid errors with browsers that don't handle console.log missing object by default. For example, Internet Explorer don't handle the missing object and ignores all scripts following the error. Unfortunately, IE will not throw any error on this condition and eat your time debugging and tracing for the invisible error.

Note 1: console object is not a standard object in ECMA Script. However, it is one of the most widely used objects by developers for debugging JavaScript programs.

Note 2: In Internet Explorer 8 and Internet Explorer 9, console object is exposed only when Developer Tools (Shortcut - F12) are opened for the active tab.

Happy Coding!




No comments:

Post a Comment

Share your comments