Writing Your First JavaScript Program

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:

  1. Open Visual Studio Code:
    • Start Visual Studio Code from your computer.
  2. 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 typing index.html.
  3. Add HTML Code:
    • Add the following code to the index.html file:
<!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.

Create a New File for HTML

Adding JavaScript to the HTML File

Next, we will create the script.js file and add our JavaScript code.

  1. Create a New JavaScript File:
    • In Visual Studio Code, click on “File” > “New File”.
    • Save this file as script.js.
  2. Add JavaScript Code:
    • Add the following code to the script.js file:
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.

  1. Install Live Server Extension:
  • Install Live Server Extension
  1. Open the HTML File in Google Chrome:
    • In Visual Studio Code, right-click on index.html and select “Open with Live Server”:
    • Run HTML via Live Server Extension
    • 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.
  2. Open Developer Tools:
    • Press Ctrl + Shift + I (Windows/Linux) or Cmd + Option + I (macOS) to open Developer Tools.
    • Go to the “Console” tab. You should see the message “Hello, World!” printed there.
    • Open Developer Tools

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.

Leave a Comment

Scroll to Top