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.
Open your web browser’s developer tools (usually by pressing F12).
Navigate to the Console tab where you can input JavaScript directly.
Type the following JavaScript command and press Enter:
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.
Create an HTML file.
Insert a <script>
tag in the HTML body.
Place your JavaScript code within the <script>
tags.
<!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.
Create an HTML element to display the output.
Give it an identifier (like id="helloWorld"
).
Use JavaScript to find that element and set its text.
<!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.
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.