🠄 Back

How to Set Up a JavaScript (JS) File

1. Create Your Project Folder

First, create a folder for your website project.

Project Folder │ ├── index.html ├── script.js └── style.css

In this example:

2. Create the JavaScript File

Create a file named:

script.js
    

Add some JavaScript code inside it:

alert("Hello from JavaScript!");
    

3. Connect the JS File to HTML

Open your index.html file and add the <script> tag before the closing </body> tag.

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>

<body>

    <h1>Hello World</h1>

    <script src="script.js"></script>
</body>
</html>
    

Illustration

HTML File │ ├── <body> │ ├── Content │ └── script.js connected here │ └── Browser runs JavaScript

4. Open the HTML File in a Browser

Double-click index.html.

Your browser will:

  1. Load the HTML page
  2. Read the linked JS file
  3. Run the JavaScript code
Browser Flow ────────────── index.html ↓ Loads script.js ↓ Runs JavaScript ↓ Shows result

5. Example: Button with JavaScript

HTML:

<button onclick="sayHello()">
  Click Me
</button>
    

JavaScript (script.js):

function sayHello() {
    alert("Hello!");
}
    

Illustration

User clicks button ↓ HTML calls sayHello() ↓ script.js runs function ↓ Alert appears

Summary