JavaScript Setup
Before building anything, you need to know where JavaScript code goes and how to run it. There are three easy ways.
On this page · 5 min · Beginner
On this page
- Learning objectives
- Explanation
- Syntax
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 27, 2026
Related tutorials
Learning objectives#
- Add JavaScript to a page with <script>
- Link an external file with defer
- Use the browser DevTools console
- Run JavaScript with Node.js
Explanation#
Inline: put code inside <script>…</script> in your HTML. Good for tiny demos.
External file: put code in app.js and load it with <script src="app.js" defer></script>. defer waits until the HTML is ready, so your code can find elements on the page. This is the recommended way.
Console: press F12 (or Ctrl+Shift+J) in any browser to open DevTools and type JavaScript directly. With Node.js installed, run node app.js in a terminal.
Syntax#
<!-- in <head> -->
<script src="app.js" defer></script>
Code example: JavaScript on a page#
<button id="btn">Say hi</button>
<p id="msg"></p>
<script>
document.querySelector('#btn').addEventListener('click', () => {
document.querySelector('#msg').textContent = 'Hi from JavaScript!';
console.log('Button clicked');
});
</script>
Clicking the button shows “Hi from JavaScript!” and logs “Button clicked”.
Step-by-step explanation#
- The HTML creates a button and an empty paragraph.
- The script finds the button with document.querySelector.
- addEventListener runs the code every time the button is clicked.
- textContent puts the message into the paragraph.
Real-world use case#
Real projects keep JavaScript in separate .js files loaded with defer, and use DevTools to debug while building.
Common mistakes#
A <script> in <head> without defer runs before the button is created, so querySelector returns null. Use defer or put the script at the end of <body>.
If app.js is in a js folder, use src="js/app.js". Check the Network tab in DevTools for 404 errors.
Best practices#
- Keep JavaScript in external files
- Load scripts with defer
- Keep DevTools open while you code
- Use VS Code with a live-server extension for instant reloads
Remember this#
defer = “wait for the HTML, then run”.
F12 opens DevTools — the Console tab is your playground.
null from querySelector usually means “the element doesn’t exist yet” or “the selector is wrong”.
Practice exercise#
Your task: Create a page with a button that logs the current time to the console when clicked.
Show solution
<button id="t">What time is it?</button>
<script>
document.querySelector('#t').addEventListener('click', () => console.log(new Date().toLocaleTimeString()));
</script>
Mini quiz#
What does the defer attribute do?
Want more? Practise all JavaScript MCQs · JavaScript interview questions
My notes#
Saved in this browser.