Day 2 of 30 of JavaScript
Shoyab khan
Posted on July 24, 2024
Hey everyone! 😊 In the last post, we introduced JavaScript. Today, we'll learn how to display data on the screen using JavaScript. Let's dive in!
There are four main ways to display data in JavaScript:
- Writing into an HTML element using
innerHTML
. - Writing into the HTML output using
document.write()
. - Writing into an alert box using
window.alert()
. - Writing into the browser console using
console.log()
.
1. Using innerHTML
Let's see this in action with a code snippet.
HTML Code:
<body>
<p></p>
</body>
JavaScript Code:
document.querySelector('p').innerHTML = "Hello World";
Output:
Explanation:
We created a paragraph element using <p></p>
without any text. The JavaScript line document.querySelector('p').innerHTML = "Hello World";
selects the paragraph element and assigns the text "Hello World" to it. innerHTML
allows us to access or modify the HTML content within an element.
2. Using document.write()
JavaScript Code:
document.write("Hello World");
Output:
Explanation:
The document.write()
method writes text or HTML directly to the document as it's being parsed or loaded. It’s mainly used for testing or dynamically generating content while the page loads. Using document.write()
after the page has loaded will overwrite the entire document content.
3. Using window.alert()
HTML Code:
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
</body>
JavaScript Code:
alert("Hello");
Output:
Explanation:
The alert()
function displays a modal dialog box with a message and an OK button. It’s used for simple notifications or alerts. However, since alert()
is a blocking function, it halts the execution of JavaScript code until the user clicks the OK button, which can disrupt the normal flow of execution.
4. Using console.log()
JavaScript Code:
console.log("Hello World");
Output:
Explanation:
The console.log()
function prints messages or values to the browser's console. It's commonly used for debugging and logging information during development. Unlike alert()
, console.log()
does not block the execution of JavaScript code.
That's all for this post! In the next one, we'll explore how comments work in JavaScript and how to create variables. Stay tuned and don't forget to follow me!
Posted on July 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.