Power of Print Statements in JavaScript: A Comprehensive Guide


Just like any other programming/scripting language, one of the most common ways to debug your code is by using print statements. In JavaScript, there are several ways to print messages to the console or to the page. In this article, we'll explore some of the most popular ways to print messages in JavaScript, including,

  • console.log()
  • console.error()
  • document.write()
  • alert()
  • window.print()

console.log()

    console.log message
    Example:
    console.log('Hello, world!');
    

    The console.log() method is the most commonly used way to print messages to the console in JavaScript. It takes one or more arguments and prints them to the console, separated by commas.

    You can also pass multiple arguments to console.log()

    Example:
    console.log('The answer is', 42);

    console.log() method can be very useful for debugging your JavaScript code, you can also print the results of function calls to the console.

    You can see the console logs using the Inspect Dev Tool of any web browser and under console tab.


console.error()

    Exmple:
    console.error('Error occurred while calculating Interest.');
    

    The console.error() method is similar to console.log(), but it's used to print error messages to the console. Error messages should be printed using the console.error() making it easier to spot them in the console.


document.write()

    Example:
    document.write('Hello, world!');

    The document.write() method should be used to print messages directly to the HTML page. It takes one argument, which is the message to be printed.


window.print()

    Example:
    window.print();

    The window.print() method is used to print the current page. When called, it opens the print dialog box, allowing the user to print the page.

    The above code will open the print dialog box, allowing the user to print the current page.

    window.print() can be useful for allowing users to print out important information from your web page.


alert()

    alert message javaScript
    Example:
    alert('Hello, world!');

    The alert() method can be used to display a message box with a message and an OK or Close button on the web browser. It takes one argument, which is the message to be displayed.

    Note: alert() can be at times useful for displaying important messages to the user, but it can also be annoying and have a bad user experience if overused.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap