javascript - javascript output - javascript print

Creating and Managing Program Output: Javascript Print Strategies

Developers use Javascript to create web content, format web pages, and return values from supporting functions that do calculations. Developers often need a way to track what Javascript code is doing, so they generate Javascript output.

The Javascript standard documents two major techniques for generating output: printing to the developer console and printing into HTML on a web page.

Javascript Printing to the Developer Console

Web browsers contain a tool called the developer console that displays debugging output from scripting languages like Javascript. Many programming languages, like Java, do something similar by directing output to a programming terminal.

The developer console contains output from Javascript errors and any other output you explicitly direct to it. Developer console output is displayed in the order it was created, and some browsers also timestamp output for easier debugging.

Javascript developer console output falls into one of three categories: normal messages, warnings, and errors. Warnings are for programming conditions that may cause errors in a program, if given the wrong inputs, but are not guaranteed to do so. Errors are fatal programming conditions developers must address to make sure a program works correctly.

There are three different Javascript functions that direct output to the developer console: console.log(), console.warn(), and console.error(). These functions accept any valid Javascript object, function, or data type and print information in a readable format to the developer console.

Console.log()

console.log() is the Javascript output function developers encounter most often. Developers often use it as a catch-all, sending messages, warnings, and error information all through the same function.

The developer console does not automatically distinguish between messages, warnings, and errors when you route them all through console.log(). Be explicit about the type of message you generate if you use console.log() this way.

It is not recommended to use console.log() for warnings and errors. Whenever possible, use console.warn() or console.error() instead.

console.log("A message.");              // String message
console.log(myWarningObject);           // Complex object as a warning
console.log(new Error("err " + myVar)); // Error string, concatenated variable

Console.warn()

console.warn() is a Javascript output function specifically for reporting warnings.

Most modern web browsers highlight output from console.warn() in yellow on the developer console. Using console.warn() is also helpful in code maintenance because the distinct function name makes it easier to distinguish warnings from errors or generic messages.

Do not create a Javascript Error object inside console.warn(). This may break functionality in the developer console because something cannot be a warning and an error at the same time.

console.warn("Potential problem here."); // String message
console.warn(myWarningObject);           // Complex object warning

Console.error()

console.error() is a Javascript output function specifically for reporting errors. Some web browsers also have a function alias called console.exception().

Most modern web browsers highlight output from console.error() in pink or red on the developer console. Like console.warn(), console.error() is helpful in code maintenance because it distinguishes messages shown on the developer console.

The Javascript Error object automatically shows a message on the developer console, so there is no reason to create an Error object inside console.error(). These two error reporting methods are essentially interchangeable.

console.error("Major problem here!");
new Error("Major problem here!");

Javascript Printing to HTML

Javascript can add new content to existing HTML on a web page, fill HTML elements, or create new HTML. Make sure that a web page can also generate content when Javascript is turned off because usability and accessibility will suffer otherwise.

Writing Inside an Element With InnerHTML()

The innerHTML() method replaces content within an HTML node without changing the rest of a document. It takes a single string parameter: simple text or valid HTML. If innerHTML() encounters an invalid HTML string, it will throw a syntax error.

let elem = document.getElementById("myElement");
elem.innerHTML("New content");

let elem2 = document.getElementById("myElement2");
elem2.innerHTML("<p>This is HTML <a href=\"#\">with a link.</a></p>");

Writing HTML Documents Directly with Document.write()

document.write() manipulates the entire HTML document, in contrast with innerHTML(). It does not work inside deferred or asynchronous scripts.

document.write() can write either text or HTML. It will not throw a syntax error if asked to write invalid HTML, so make sure that any HTML passed to document.write() is valid.

Calling document.write() before the entire HTML document has been loaded will completely rewrite the document.

<!doctype html>
<html lang="en">
    <head>
        <title>Example</title>
        <script>
function moreContent() {
    document.open();
    document.write("<h1>Out with the old, in with the new!</h1>");
    document.close();
}
        </script>
    </head>
    <body onload="moreContent();">
        <p>Doc content.</p>
    </body>
</html>

Calling document.write() from an inline HTML script after the rest of the HTML nodes are loaded will append its text to the document.

<!doctype html>
<html lang="en">
    <head>
        <title>Example</title>
    </head>
    <body onload="moreContent();">
        <p>Doc content.</p>
        <script>
document.write("<p>This is more text.</p>");
        </script>
    </body>
</html>

Javascript Print vs. Javascript Output

Novice developers often use the words “print” and “output” interchangeably, but you should be careful to remember the difference between them. Printing refers to activating a hardware device that produces hard copies or some other physical media. Output refers to generating content on a web page or on the developer console.

The window.print() function opens a browser’s print dialog box with the active content, but there is rarely a reason to do this in production code. It may be useful in testing.

Conclusion

Javascript output generates content on web pages and information in the developer content for debugging. As a Javascript developer, you should categorize output carefully, using the appropriate functions to show messages, errors, and warnings.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript output strategies and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni