Answer: Use internal JavaScript for small, page-specific code; use external JavaScript (a separate .js file) when the code is long or shared by several pages.
Internal JavaScript is written inside a <script> tag in the HTML page:
<script>
alert("Hello");
</script>
Use it when the script is short, used on only one page, or for quick testing. No extra file request is needed.
External JavaScript is kept in a separate file and linked with the src attribute:
<script src="app.js"></script>
Use it when:
- the same code is needed on many pages (write once, reuse);
- the code is large, so HTML and JavaScript stay separate and easier to maintain;
- you want faster repeat visits, because the browser caches the .js file.