The use of a .js file as an external file

A .js file as an external file:

 

What it is:
A .js file is a JavaScript file—basically, it contains code that makes your webpage interactive (like buttons working, menus opening, etc.).

Why use it externally?

Instead of writing JavaScript directly in your HTML file, you write it separately in a .js file to keep things clean and organized.

How to use it in HTML:

<script src=”script.js”></script>

  • script.js is the name of your external JavaScript file.
  • Place this line inside the <head> or at the end of the <body> in your HTML file.

Example:

html
<!– index.html –>
<html>
<head>
<script src=”script.js”></script>
</head>
<body>

<button onclick=”sayHello()”>Click me</button>

</body>
</html>

JavaScript
// script.js
function sayHello() {
alert(“Hello there!”);
}

Now your button is using  the external JavaScript file to show the alert!