Creating your first JavaScript program
Your first JavaScript program can be a few lines that run in the browser: print a message to the console, read something from the page and change what the user sees. All you need is a text editor and a browser. Building it from two small files, an HTML page and a script, teaches the basic loop you will repeat constantly: write code, reload, check the console, fix and try again.
Setting up two files
Create a folder with index.html and app.js. Keeping JavaScript in its own file, instead of inside the HTML, makes it easier to read and reuse.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My first script</title>
<script src="app.js" defer></script>
</head>
<body>
<h1 id="greeting">Hello</h1>
<label for="name">Your name</label>
<input id="name" type="text">
<button id="say-hi" type="button">Say hi</button>
</body>
</html>
The defer attribute tells the browser to run the script after the HTML has been parsed, so the elements exist when the code looks for them.
Writing the script
console.log('Script loaded');
const heading = document.getElementById('greeting');
const nameInput = document.getElementById('name');
const button = document.getElementById('say-hi');
button.addEventListener('click', () => {
const name = nameInput.value.trim();
if (name === '') {
heading.textContent = 'Please type your name first';
return;
}
heading.textContent = `Hello, ${name}!`;
console.log('Greeted', name);
});
This small program already uses the main ideas: const variables, selecting elements, listening for an event, reading input, a condition and updating the page. The backticks create a template literal, which inserts the variable with ${...}.
Running it and reading the console
Open index.html in your browser by double-clicking it or dragging it into a tab. Then open developer tools (F12, or right-click and choose Inspect) and switch to the Console tab. You should see "Script loaded". Type a name, click the button and watch both the heading and the console update.
The console is also a playground. Type 2 + 3, 'abc'.toUpperCase() or heading.textContent and press Enter to see the result immediately. Try ideas there before writing them in your file.
Errors you will probably hit first
The most common first error is Cannot read properties of null. It means getElementById found nothing, either because the id is misspelled (ids are case-sensitive) or because the script ran before the HTML loaded. Using defer, or placing the script tag just before </body>, fixes the timing problem.
Next is the script not loading at all. Check the Network or Console tab for a 404 on app.js; usually the file name or folder in src does not match. Another frequent one is a red SyntaxError pointing at a line with a missing bracket or quote. The console shows the file and line number; click it to jump to the problem.
Finally, remember that saving the file does not refresh the page. Reload the browser after every change.
Small experiments to try next
- Change the heading colour with
heading.style.color = 'teal'. - Count how many times the button was clicked and show the number.
- Greet the user when they press Enter in the input by listening for the
keydownevent. - Show the name in capitals using
toUpperCase().
The pattern you just learned
Load a script with defer, find elements, listen for events, read values and update the page, then check the console whenever something does not work. Almost every interactive feature you build later follows this same shape.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.