Basic Output in JavaScript
JavaScript provides several ways to display information. These methods are essential for beginners to understand how their code works.
1. Using console.log()
console.log()
prints messages to the browser console. It is mainly used for debugging or checking values.
console.log("Hello, World!");
2. Using alert()
alert()
shows a pop-up message in the browser.
alert("Welcome to JavaScript!");
3. Using document.write()
document.write()
writes content directly to the webpage.
document.write("Hello, this is JavaScript output!");
Try It Yourself
Follow these steps to practice JavaScript:
1. Create an HTML file (index.html
)
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<h1>Learn JavaScript</h1>
<button onclick="sayHello()">Click Me!</button>
<p id="output">Waiting...</p>
<script src="script.js"></script>
</body>
</html>
2. Create a JavaScript file (script.js
)
function sayHello() {
console.log("Button clicked!");
alert("Hello, JavaScript!");
document.getElementById("output").innerHTML = "You clicked the button!";
}