DEV Community

Shoyab khan
Shoyab khan

Posted on

Day 2 of 30 of JavaScript

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!

Image description

There are four main ways to display data in JavaScript:

  1. Writing into an HTML element using innerHTML.
  2. Writing into the HTML output using document.write().
  3. Writing into an alert box using window.alert().
  4. 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>
Enter fullscreen mode Exit fullscreen mode

JavaScript Code:

document.querySelector('p').innerHTML = "Hello World";
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

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");
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

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>
Enter fullscreen mode Exit fullscreen mode

JavaScript Code:

alert("Hello");
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

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");
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

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!

Top comments (0)