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('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('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.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!


Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!