JavaScript Output
JavaScript does not have a built-in print or output function.
Displaying Data in JavaScript
JavaScript can output data in several ways:
- Using window.alert() to display a pop-up alert box.
- Using document.write() to write content directly into the HTML document.
- Using innerHTML to write content into an HTML element.
- Using console.log() to write output to the browser's console.
Using window.alert()
You can display data by showing a pop-up alert box:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Manipulating HTML Elements
To access an HTML element from JavaScript, you can use the document.getElementById(*id*)
method.
Use the id
attribute to identify the HTML element, and innerHTML
to get or set the element's content.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My first paragraph</p>
<script>
document.getElementById("demo").innerHTML = "The paragraph has been changed.";
</script>
</body>
</html>
The JavaScript statements above (inside the <script>
tag) can be executed in a web browser:
document.getElementById("demo") is JavaScript code that finds an HTML element using its id
attribute.
innerHTML = "The paragraph has been changed." is JavaScript code used to modify the HTML content (innerHTML
) of the element.
In This Tutorial
In most cases throughout this tutorial, we will use the methods described above to output data.
The example above directly writes the <p>
element with id="demo"
to the HTML document.
Writing to the HTML Document
For testing purposes, you can write JavaScript directly into the HTML document.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(Date());
</script>
</body>
</html>
Use document.write()
only to output content to the document.
If document.write()
is executed after the document has finished loading, it will overwrite the entire HTML page.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="myFunction()">Click Me</button>
<script>
function myFunction() {
document.write(Date());
}
</script>
</body>
</html>
Writing to the Console
If your browser supports debugging, you can use console.log() to display JavaScript values in the browser console.
Press F12 to open the developer tools in your browser, then click the Console tab.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
let a = 5;
let b = 6;
let c = a + b;
console.log(c);
</script>
</body>
</html>
Did You Know?
Debugging in programming is the process of testing, finding, and reducing bugs (errors) in your code.