JavaScript BasicsCore· 30 min read

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).

Internal JS in a <script> tag
<script>
  document.write("Hello from internal JavaScript!");
</script>
Live preview

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!

Link an external script.js
<!-- 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.

console.log → console; document.write → page
<script>
  console.log("This prints to the browser console (press F12).");
  document.write("This prints to the page.");
</script>
Live preview

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?

Answer: Placing the script just before </body> ensures the HTML elements exist before the script runs and tries to use them.

✍️ Practice

  1. Create an external script.js file, link it, and have it console.log a message.
  2. Open the console (F12) and read your message.

🏠 Homework

  1. Write a script that prints your name to the console and a greeting to the page.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →