JavaScript Output

JavaScript Output defines the ways to display the output of a given code. JavaScript can "display" data in different ways:  

a) Writing into an HTML element, using innerHTML
b) Writing into the HTML output using the document.write()
c) Writing into an alert box, using a window.alert().
d) Writing into the browser console, using console.log().

JavaScript

a) Using innerHTML

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>

<h2>My First Web Page</h2>
<p>My First Paragraph.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html> 

Output:


Changing the innerHTML property of an HTML element is a common way to display data in HTML.

b) Using document.write()

For testing purposes, it is convenient to use the document.write():

Example:

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My first paragraph.</p>

<p>Never call document.write after the document has finished loading.
It will overwrite the whole document.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html> 

Output:


The document.write() method should only be used for testing. 

c) Using window.alert()

You can use an alert box to display data:

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html> 

Output:


d) Using console.log()

For debugging purposes, you can use the console.log() method to display data: 

<!DOCTYPE html>
<html>
<body>

<h2>Activate debugging with F12</h2>

<p>Select "Console" in the debugger menu. Then click Run again.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html> 

Output:

Enjoy!


Comments

Popular Posts