Running JavaScript (Browser, Script Tag, External Files)
There are multiple ways to run JavaScript — directly in the browser console, embedded in HTML with script tags, or in external files. Understanding these methods is essential before writing real code.
Ways to Run JavaScript
- Browser Console — Press F12 → Console tab. Type JavaScript directly. Best for quick testing and debugging
- Inline Script — <script> tag inside HTML: <script>console.log('Hello');</script>. Runs when the page loads
- External File — <script src='app.js'></script>. Separate .js file linked in HTML. Best practice for real projects
- Script Placement — Place <script> before </body> or use defer attribute. Ensures HTML loads before JS runs
- defer vs async — defer: loads in parallel, runs after HTML parsed. async: loads and runs immediately (use for independent scripts)
Script Tag Examples
<!-- Method 1: Inline script -->
<script>
console.log("Hello from inline script!");
</script>
<!-- Method 2: External file (recommended) -->
<script src="app.js"></script>
<!-- Method 3: With defer (best practice) -->
<script src="app.js" defer></script>
<!-- Method 4: With async (independent scripts) -->
<script src="analytics.js" async></script>
<!-- Why defer? Without it, JS may run before HTML is ready -->
<!-- <script defer> waits for HTML to finish loading first -->Tip
Tip
Always place script tags before </body> or use the defer attribute in the <head>. This ensures HTML content loads first, preventing errors when your JavaScript tries to access elements that haven't been created yet.
Every website works on this model
Common Mistake
Warning
Placing script tags in the <head> without defer, then wondering why document.getElementById returns null. The script runs before the HTML body is parsed, so the elements don't exist yet when the JS tries to find them.
Practice Task
Note
Create an HTML file and test both approaches: (1) Put a script in <head> without defer that tries to access a body element — watch it fail. (2) Add the defer attribute and see it work correctly. This demonstrates why script placement matters.
Quick Quiz
Key Takeaways
- There are multiple ways to run JavaScript — directly in the browser console, embedded in HTML with script tags, or in external files.
- Browser Console — Press F12 → Console tab. Type JavaScript directly. Best for quick testing and debugging
- Inline Script — <script> tag inside HTML: <script>console.log('Hello');</script>. Runs when the page loads
- External File — <script src='app.js'></script>. Separate .js file linked in HTML. Best practice for real projects