Writing JavaScript
JavaScript can "display" data in different ways:
- Writing into the browser console, using console.log().
- Writing into the HTML output using document.write().
- Writing into an HTML element, using innerHTML.
- Writing into an alert box, using window.alert().
Writing Output to Browser Console
You can easily output a message or write data to the browser console using the console.log() method. This is a simple, but very powerful method for generating detailed output. Here's an example:
Eg:
<script>
console.log("Hello World!"); // Prints: Hello World!
</script>
Writing Output to the Browser Window
You can use the document.write() method to write the content to the current document only while that document is being parsed.
Eg:
<script>
document.write("Hello World!"); // Prints: Hello World!
</script>
Inserting Output Inside an HTML Element
You can also write or insert output inside an HTML element using the element's innerHTML property. However, before writing the output first we need to select the element using a method such as getElementById().
Eg:
<script>
document.getElementById("pargra").innerHTML = "Hello World!";
</script>
Displaying Output in Alert Dialog Boxes
You can also use alert dialog boxes to display the message or output data to the user. An alert dialog box is created using the alert() method.
Eg:
<script>
alert("Hello World!"); // Outputs: Hello World!
</script>