Chapter 01

JavaScript Where to Write

JavaScript can be added to an HTML page in different ways, including inline, internal, and external JavaScript.

What is JavaScript Where to Write?

  • JavaScript can be written directly inside an HTML event attribute.
  • JavaScript can be written inside a <script> tag in the same HTML file.
  • JavaScript can be written in a separate .js file and connected to HTML.
  • External JavaScript files are generally preferred for larger projects because they keep code organized and reusable.

Syntax

<script>
    // JavaScript code
</script>

<!-- External JavaScript file -->
<script src="script.js"></script>

Example

Try understanding this code before running it.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript File Example</h2>
<button onclick="sayHello()">Click Me</button>

<script>
function sayHello() {
    alert('Hello Student!');
}
</script>
</body>
</html>

Important Points

  • Inline JavaScript is useful for very small examples.
  • Internal JavaScript is written in the same HTML file.
  • External JavaScript is written in a separate .js file.
  • External files make code easier to organize, maintain, and reuse.

Common Mistakes

  • Forgetting to close the script tag.
  • Using the wrong path for an external JavaScript file.
  • Using the wrong file extension instead of .js.

Real-World Use

Professional websites commonly use external JavaScript files for reusable application logic.

Practice Exercise

Practice: Adding JavaScript
Create a button and use internal JavaScript to display an alert message when the button is clicked.

Ready to write code?

Open the JavaScript editor and run your code with live output.

Try It Yourself →