JavaScript Program to Print Hello World

Updated on September 30, 2024
Print Hello World header image

Introduction

Writing a simple JavaScript program to print "Hello World" is one of the fundamental steps in starting with programming in JavaScript. This small program encapsulates the basic structure and syntax of the language, making it a perfect starting point for beginners.

In this article, you will learn how to write a "Hello World" program in JavaScript through several examples. These will include outputting the text to the console, displaying it on a web page, and even logging it into an HTML element. Each method gives a different insight into how JavaScript can interact with the web environment.

JavaScript Console Output

  1. Open your web browser’s developer tools (usually by pressing F12).

  2. Navigate to the Console tab where you can input JavaScript directly.

  3. Type the following JavaScript command and press Enter:

    javascript
    console.log('Hello World');
    

    This line of code will print "Hello World" to the browser console. console.log() is a function that prints any specified information to the console.

JavaScript in HTML

Display in the Web Page Directly

  1. Create an HTML file.

  2. Insert a <script> tag in the HTML body.

  3. Place your JavaScript code within the <script> tags.

    html
    <!DOCTYPE html>
    <html>
    <head>
        <title>Hello World Program</title>
    </head>
    <body>
        <script>
            document.write('Hello World');
        </script>
    </body>
    </html>
    

    This snippet will directly write "Hello World" on the web page as it loads. document.write() is a method that writes a string directly to the HTML document.

Update HTML Element with JavaScript

  1. Create an HTML element to display the output.

  2. Give it an identifier (like id="helloWorld").

  3. Use JavaScript to find that element and set its text.

    html
    <!DOCTYPE html>
    <html>
    <head>
        <title>Hello World Program</title>
    </head>
    <body>
        <div id="helloWorld"></div>
        <script>
            document.getElementById('helloWorld').innerText = 'Hello World';
        </script>
    </body>
    </html>
    

    In this example, the div element with id helloWorld gets updated by JavaScript to show "Hello World". The getElementById() method selects the element by ID and the innerText property sets the text inside that element.

Conclusion

Starting with a simple "Hello World" program in JavaScript, you explored how to use the console, include JavaScript in an HTML page, and dynamically update HTML elements with JavaScript code. These examples serve as a practical introduction to JavaScript programming and its interaction with web documents. By mastering these fundamental techniques, you lay a solid foundation for more advanced JavaScript programming and web development tasks.