JavaScript has evolved a long way in recent years. Browsers are becoming more robust, and machines are becoming more powerful. Pair this with the recent development of Node.js for the execution of JavaScript on servers, and we can understand why NodeJS has exploded in popularity. Naturally, our ability to effectively debug code grows increasingly as the scale of the codebase grows.
Logging messages to the console is a time-tested way to diagnose and troubleshoot issues in the codebase. Hence Logging functionality is crucial for every programming language. Although JavaScript has a console.log for performing essential debugging functions, its browser’s console comes with several other powerful functions to perform debugging. In this regard, multiline logging plays a vital role in the same, as it is very much required to categorize the logs and make them more readable.
For more insight into JavaScript’s libraries for web development, you can dive into the node js training online, which goes into full detail.
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
- Writing into an HTML element, using innerHTML is responsible for in-page browser printing, which is displayed on the web page. This is a fundamental and crude way to go forward and lacks additional functionalities, it still works fine in place and is used extensively to log basic texts.
- Writing into the HTML output using a document.write() - It works pretty similar to innerHTML but is somewhat more restrictive as in inner HTML, we can print modified data as well.
- Writing into an alert box, using a window.alert() - It is customizable with a separate structure, so it is easy to understand, but the display window is separate; you also will need to handle categories manually.
- Writing into the browser console, using console.log() - It is the most commonly used practice, with several categories of logs.
Given these options, we can quickly go for any logging situation comparable to Java’s System.out.println(). These possibilities enable us to replicate a println javascript scenario. Let's discuss in depth each of the options below.
Using innerHTML
The innerHTML property is a part of the Document Object Model (DOM) and can be used to write the dynamic HTML on the HTML document. It is usually used to set or return the HTML content of an element. Moreover, it helps the web pages to generate components such as registration forms, comment forms, links, etc. However, this same property of the innerHTML can be exploited to print logs as well. Changing the innerHTML property of an HTML element is the most common way to display data in HTML. There are several ways to do so, but all essentially revolve around the same basis of getting the element from the document and using the innerHTML property on the same.
To access an HTML element, JavaScript can use the
document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content. Example -
<!DOCTYPE html>
<html>
<body>
<p>Sample Paragraph</p>
<p id="print"></p>
<script>
document.getElementById("print").innerHTML = "Hello World";
</script>
</body>
</html>
Despite being a very simple and in-house logging mechanism, it is not advisable to use it for complex scenarios. Below are a few disadvantages of using inner HTML.
- Slow Processing: Using innerHTML is way slower than other options. Its contents are slowly created because already parsed contents and elements are also re-parsed, which raises the overall latency. Any content addition, append, deletion, or modification on a web page using innerHTML results in their replacement; the DOM nodes are also reparsed and recreated.
- Manual Event Handler Management: Event handlers are not attached by default to the new elements created by setting innerHTML. It is required to maintain track of the event handlers and adhere to new features manually. This can be a cause of memory leaks in some of the browsers.
- Appending to innerHTML is not supported: The += operator is generally used for appending in JavaScript. But on appending to an Html tag using innerHTML, the whole tag is re-parsed. String concatenations also do not perform well in terms of scalability in case dynamic DOM elements are required to be created as the plus and quote openings and closings become difficult to track.
- Document Break Vulnerability: There is a lack of a proper default validation provided by the innerHTML property, so typically, any valid HTML snippet can be used. This can break the document of JavaScript in several cases. Even snippets of broken HTML can also be used, which may lead to unexpected scenarios, XSS attacks, and loss of sensitive information.
Using document.write()
The document.write() method writes a string of text to a document stream opened by the document.open(). This open document object stream provides a way to display output, and the document.write() call inserts text into the document (the browser window’s web page). Example -
<!DOCTYPE html>
<html>
<script>
function printSomething() {
document.open();
document.write("<p> Hello World </p>");
document.close();
</script>
<body onload="printSomething();">
</body>
</html>
Document object has one more method that mirrors println javascript. It is the document.writeln() method adds a new line after each print statement. Also, it supports direct rendering of HTML if added in case of a string, just as mentioned in the example above.
However the use of document.write(), is advised for testing purposes only, as document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document. This can impact the chain with severe loss of data. Also using document.write() after an HTML document is loaded, will delete all existing HTML. It is rather an old school and hardly used anymore since it requires embedding in the actual page, which is discouraged currently. The aim is to maintain a separation of concerns, meaning no presentational elements or behaviors are embedded in the page, only HTML.
Also, it means that we have to call documents.write() from an inline script block, preventing the browser from processing parts of the page that follow. Scripts and images will not be downloaded until the writing block is finished. Also, you can check out the full stack development to work and experience everything in action.
Using window.alert()
This is as simple as using an alert box to display logging data. The function window.alert() instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.
<!DOCTYPE html>
<html>
<body>
<p>Sample Paragraph</p>
<script>
window.alert("Hello World");
</script>
</body>
</html>
The Output is something like this.
The window keyword can also be skipped as in JavaScript, the window object is the global scope object, that means variables, properties, and methods by default belong to the window object. This means that specifying the window keyword is optional.
However, this also comes with its own complications, be it super simple. The main issue with the usage is self-evident that it is separate. The alert box takes the focus away from the current window and forces the user to read the message.
Hence it is advised not to overuse the method. Dialog boxes are modal windows as it prevents the user from accessing other parts of the page until the alert box is closed. The perfect use case falls if someone wants to track errors generated.
Using console.log()
The most commonly used function for logging is the console.log(). It is widely used specifically for debugging purposes because of the feature packed and simple. JavaScript print to console displays the output to the browser’s embedded console. Every current web browser comes built-in with its console, tools, or developer console. These consoles can sometimes even run JavaScript directly as well. Google Chrome has the Chrome DevTools Console; Firefox has a Web Console as a sub-menu of Web Developer, and a console tab under the Develop menu in Safari. The usage can be seen as follows:
<!DOCTYPE html>
<html>
<body>
<script>
console.log("Hello World");
</script>
</body>
</html>
The Dev tools in chrome can be accessed using inspect.
Let’s see the Logged output for the previous HTML file.
This output checking in a separate part is a disadvantage with console.log(), followed by the fact that it will be shown to everyone browsing the page. Some browsers may not like those logs, and we could encounter errors on production websites if we forget to remove them. So, it is advised to be careful of what we log.
But even though this function is very versatile. There are several advantages to the same:
- Multiple Values: console.log() can include multiple values. Generally, a string tag is added to the beginning to identify what it is we are logging easily. E.g
let x = 101
let y = 202
let z = 303
console.log("x:", x, "y:", y, "z:", z)
console. log({x, y, z})
- Supports Object Data Logging: The first log will print the properties within the user object. The second will identify the object as a "user" and print the properties within it.
let object = {
objName: 'Object1',
objSubInfo: {
id: 456
}
}
console.log(object)
console.log({object})
- Formatted output: We can also use formatted output and use variables for the same.
console.log("%s has %d days.", "January", 31)
Apart from basic logging, the console object has a plethora of methods that are usually underutilized but are extremely beneficial and useful. The most valuable is the message levels. JavaScript intrinsically has support for logging messages at various levels, similar to other programming languages. The different logging message levels provided and supported by JavaScript are:
- Plaintext : log() : This is the most common and primary method and can be used for plaintext. Output is unstyled plain text.
- Info : info() : This is the method for info based message levels. Output is displayed in blue text color.
- Warn : warn() : This is the method for the warning message level. This level is similar to plaintext but hints the developer for attention and often comes with stack traces to guide us in the debugging sessions. We can usually use this when something unanticipated happens. Output is displayed in yellow text color.
- Error : console.error() : This is the method for error message level. It is advised to use this message when a huge or an application-breaking error happens. Output is displayed in red text color.
Apart from this, there are several other options like message grouping using console.group() and console.groupEnd(), logging time using console.time(), console.timeLog(), console.TimeEnd(), optional log using console.assert(), counting and many more.
Console can also display JSON in tabular format and also, we can clear the console using console.clear() as well. This, in short, makes the console the most versatile option for printing in JavaScript.
JavaScript Print
JavaScript does not have any print object or print methods, as it is not possible to access output devices from JS.
The only exception which we have is that we can call the window.print() method in the browser to print the content of the current window.
<!DOCTYPE html>
<html>
<body>
<button onclick="window.print()">Print Page Contents</button>
</body>
</html>
Looking to kickstart your coding journey? Discover the best beginner Python course that will ignite your passion for programming. Unleash your creativity and unlock endless possibilities with Python's simplicity and versatility. Join us now and embark on an exciting learning adventure!
Conclusion
Using effective and efficient logging mechanisms is one of every web developer's most crucial skills under their sleeves. Client-side logging functionality is only a small part of the entire development process, yet it is important.
Using the logging functionalities helps developers develop codes more efficiently and debugging sessions. To learn about more JavaScript functions found on the different browsers’ consoles, navigate to the MDN’s documentation to get an in-depth overview of them.
The most advisable and readable way to log is to use console.log() and its color-coded multiple variations during the development process and several other available options. Also, the Equivalent of Println in JavaScript is document.writeln() for the closest, but it is not advisable in all cases due to its varied limitations. Remember, you can further explore knowledgehut node js training online which goes in full detail about the same, and check out the full stack training to work and experience everything in action.