Where to Put JavaScript
Inline, internal or external — and why your script usually goes at the end of the body.
What you will learn
- Add JS with the <script> tag
- Link an external .js file
- Use the browser console
The script tag
JavaScript goes inside a <script> tag. You can write it directly in the HTML, or link an external .js file (the professional way).
<script>
document.write("Hello from internal JavaScript!");
</script>Anything between <script> and </script> is JavaScript. Here document.write(...) tells the browser to write that text straight onto the page. The text in quotes is exactly what appears.
Note: Output: Hello from internal JavaScript!
<!-- External file (the professional way) -->
<script src="script.js"></script>This version has no code inside the tag. Instead src="script.js" points to a separate file that holds the JavaScript. The browser fetches and runs that file. Keeping JS in its own file is tidier and lets many pages share the same code.
Tip: Put your <script> tag just before </body>. That way the HTML loads first, so your JavaScript can find the elements it needs to work with.
The console — your best friend
Press F12 in your browser and open the Console tab. console.log() prints messages there — it is how developers check values and debug.
<script>
console.log("This prints to the browser console (press F12).");
document.write("This prints to the page.");
</script>Two different outputs from two different commands. console.log(...) writes its message to the hidden console (you only see it after pressing F12). document.write(...) writes onto the visible page. Same idea — printing text — but to two different places.
Note: Output: On the page: This prints to the page. In the console: This prints to the browser console (press F12).
Note: In these live previews we mostly use document.write or change the page so you can see the result here. In your own projects, console.log is the everyday tool for checking values.
Q. Where is the best place to put your <script> tag?
✍️ Practice
- Create an external
script.jsfile, link it, and have itconsole.loga message. - Open the console (F12) and read your message.
🏠 Homework
- Write a script that prints your name to the console and a greeting to the page.