Chapter 01
JavaScript Where to Write
JavaScript can be added to an HTML page in different ways, including inline, internal, and external JavaScript.
01 • Learn
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.
02 • Syntax
Syntax
<script>
// JavaScript code
</script>
<!-- External JavaScript file -->
<script src="script.js"></script>
03 • Example
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>
04 • Remember
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.
05 • Avoid
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.
06 • Practical
Real-World Use
Professional websites commonly use external JavaScript files for reusable application logic.
07 • Practice
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.