3. Running JavaScript Code
There are three main ways to execute JavaScript code in a web environment.
1. External Script (Best Practice)
We link an external .js file to our HTML document. This keeps the HTML and JS separate and clean.
In index.html:
html
<!DOCTYPE html> <html> <head> <title>My First JS Project</title> </head> <body> <h1>Hello JavaScript!</h1><!-- The script tag usually goes just before the closing </body> tag -->
<script src="app.js"></script>
</body>
</html>
In app.js:
javascript console.log('Script is running!');
2. Internal Script
Embedding the JS directly within <script> tags in the HTML.
html
<script> console.log('This is internal JS.'); </script>Note: Avoid this method for larger projects.