The JavaScript Hello World program is a basic example used to introduce the language and demonstrate how to display output.
- Prints the text "Hello, World!" to the screen.
- Helps beginners understand basic syntax and script execution.
Ways to Print Hello World in JS
JavaScript can be run in three common ways, based on whether you’re testing code, building small demos, or developing real-world applications.
1. Using the Browser Console
One of the simplest ways to run JavaScript is by using the browser’s built-in console, available in modern browsers like Chrome, Firefox, and Edge, which lets you execute JavaScript directly.
Steps:
- Open your web browser (e.g., Google Chrome).
- Press F12 or Ctrl+Shift+I (Windows/Linux) or Cmd+Opt+I (Mac) to open the Developer Tools.
- Go to the Console tab.
- Type the following JavaScript code:
console.log("Hello, World!");
2. Using an HTML File
JavaScript can also be executed within a web page by embedding it directly into an HTML document, which is the standard approach for adding interactivity and dynamic behavior to websites.
Steps:
- Open any text editor (e.g., Notepad, Sublime Text, VS Code).
- Create a new file and save it with the .html extension (e.g., hello-world.html).
- Write the following code.
- Save the file and open it in a web browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World in JavaScript</title>
</head>
<body>
<script>
alert("Hello, World!");
</script>
</body>
</html>
3. External JavaScript File
For larger applications, it’s a good practice to separate JavaScript code into external files. This helps with better organization and reusability.
Steps:
- Create an index.html file for the webpage structure and a script.js file to hold the JavaScript code, linking the script file to the HTML document.
- Write the following code in the hello-world.html file.
- Save both files in the same directory and open the html file in a browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World in JavaScript</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
console.log("Hello, World!");