How to Use JavaScript in HTML

Subject: JavaScript

To make your webpages interactive, you need to include JavaScript in your HTML documents. JavaScript can be added in three different ways:

  • Inline JavaScript
  • Internal JavaScript
  • External JavaScript

Each method has its use cases depending on the size, structure, and complexity of your application.

1. Inline JavaScript

In this method, JavaScript is directly written within an HTML element using the on-event attributes such as onclick, onmouseover, etc.

Example: Inline JavaScript

Use Case: Suitable for small actions like form validation or button alerts. Not recommended for large applications due to maintainability and readability concerns.

2. Internal JavaScript

Internal scripts are written inside the <script> tag placed within the <head> or <body> section of the HTML document.

Example: Internal JavaScript in <head>

Use Case: Useful for writing page-specific scripts. Keeps JavaScript separate from HTML content but still inside the same file.

3. External JavaScript

JavaScript is written in a separate .js file and linked using the <script src="filename.js"> tag.

HTML File (index.html)

External JavaScript File (script.js)

Best Practice: Keeps HTML and JavaScript code organized and modular. Promotes reusability and cleaner code separation.

Script Placement: Head vs. Body

You can place the <script> tag in either:

  • <head>: Loads before the HTML is rendered. Might delay page content if the script is large.
  • Bottom of <body>: Recommended — allows HTML content to load first.

Key Takeaways

  • JavaScript can be embedded inline, internally, or externally in HTML.
  • Inline JavaScript is simple but not scalable.
  • Internal JavaScript allows better structure for single pages.
  • External JavaScript is the most scalable and maintainable approach.
  • Always prefer placing scripts at the end of <body> or using defer/async for better performance.
Next : JS Output