Equivalent of Java Println to Print Output in JavaScript
-
Use the
console.log()
Method to Print Output in JavaScript -
Use the
document.write()
Method to Print Output in JavaScript -
Use the
alert()
Method to Print Output in JavaScript
The infer methods in JavaScript are quite different from traditional programming language output functions. Other languages execute program files and receive results via one print
function; JavaScript deals with web browsers and incorporates them.
In our examples, we will examine three ways of outputting a message. It can be a string or variable data.
We will have an instance with the console.log()
, document.write()
, and alert()
methods to print out a result. Let’s hop into the codebases.
Use the console.log()
Method to Print Output in JavaScript
JavaScript console.log()
method writes messages (logs) to the console. It is used for testing; we will print a string in our drive and see how it behaves.
Generally, console.log()
showcases the output in an HTML tree format. Another functions similar to console.log()
is the console.dir()
.
But console.dir()
results in JSON tree format. You can check the difference in your web console.
Code Snippet:
console.log('Howdy! We are writing on console')
console.dir('Howdy!')
Output:
Use the document.write()
Method to Print Output in JavaScript
The document.write()
method is corporated with HTML DOM. So, it will not print the result in the consoles but will write directly in the HTML body, aka in the webpage.
It can take variables, strings, booleans, etc., as its arguments. Let’s check the example.
Code Snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
var x = 42;
document.write("It's a message " + x)
</script>
</body>
</html>
Output:
Use the alert()
Method to Print Output in JavaScript
In JavaScript, we get to prompt the window to display messages on some actions. The alert()
method is joined with the window
object.
And whenever it is triggered, a dialog box pops up on the screen, and the expected message is previewed.
Let’s go through the example. We are using Jsbin to examine the instances.
Code Snippet:
alert('Code Red Alert!')
Output: