In this chapter, we will write our first JavaScript program. We will cover:
- Creating an HTML File
- Adding JavaScript to the HTML File
- Running the JavaScript Program
Creating an HTML File
To run JavaScript, you need an HTML file. Here’s how to create one:
- Open Visual Studio Code:
- Start Visual Studio Code from your computer.
- Create a New File:
- Click on “File” in the menu and select “New File”.
- Save this file as
index.html
by clicking “File” > “Save As” and typingindex.html
.
- Add HTML Code:
- Add the following code to the
index.html
file:
- Add the following code to the
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My First JavaScript Program</title> </head> <body> <h1>Hello, JavaScript!</h1> <script src="script.js"></script> </body> </html>
This code sets up a simple HTML page with a title and a heading. The <script>
tag includes an external JavaScript file named script.js
.
Adding JavaScript to the HTML File
Next, we will create the script.js
file and add our JavaScript code.
- Create a New JavaScript File:
- In Visual Studio Code, click on “File” > “New File”.
- Save this file as
script.js
.
- Add JavaScript Code:
- Add the following code to the
script.js
file:
- Add the following code to the
console.log("Hello, World!");
This code will print “Hello, World!” to the console when the HTML file is opened in a web browser.
Running the JavaScript Program
Now, we will run our JavaScript program by opening the HTML file in Google Chrome.
- Install Live Server Extension:
- Open the HTML File in Google Chrome:
- In Visual Studio Code, right-click on
index.html
and select “Open with Live Server”: - If you haven’t installed the Live Server extension, then you can manually open the file in Google Chrome by navigating to the file location and double-clicking on
index.html
.
- In Visual Studio Code, right-click on
- Open Developer Tools:
- Press
Ctrl + Shift + I
(Windows/Linux) orCmd + Option + I
(macOS) to open Developer Tools. - Go to the “Console” tab. You should see the message “Hello, World!” printed there.
- Press
Conclusion
Congratulations! You have written and run your first JavaScript program. You created an HTML file, added JavaScript code to it, and saw the output in the browser’s console. This is the foundation for building more complex JavaScript programs. In the next chapters, we will dive deeper into JavaScript and learn more about its features and capabilities.