Learn JavaScript Step by Step Tutorial with Real Examples
Follow a hands-on tutorial that teaches JavaScript by building a real interactive page. Write your first variables, functions, and event listeners with examples you can run.
The best way to learn JavaScript step by step is to build something with it. This tutorial walks you through creating a working interactive page from scratch. You will write real code, see real results, and understand every line.
By the end, you will have built a page that takes user input, runs a calculation, and updates the screen -- the core pattern behind every web application.
What You Will Build
A simple tip calculator. The user enters a bill amount and a tip percentage, clicks a button, and sees the tip amount and total.
The app is small on purpose. Once you understand the pattern -- read input, do math, show output -- you can apply it to any idea.
Step 1: Create the HTML Structure
Start with a plain HTML page. Every page needs this minimal shell before any content goes inside it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tip Calculator</title>
</head>
<body>
</body>
</html>Now add the interactive elements inside the empty body tags above. This is the skeleton that JavaScript will interact with later: two number inputs for the bill and tip, a button to trigger the calculation, and an empty paragraph to hold the result.
<h1>Tip Calculator</h1>
<label for="bill">Bill amount ($):</label>
<input type="number" id="bill" placeholder="0.00">
<label for="tip">Tip percentage (%):</label>
<input type="number" id="tip" placeholder="15">
<button id="calculate">Calculate</button>
<p id="result"></p>
<script src="app.js"></script>Each input and the button carry an id attribute, which is how JavaScript will find them. The result paragraph starts empty, and JavaScript fills it in later. The script tag at the bottom links the JavaScript file, and placing it last means the HTML loads first.
Save the full page as index.html.
Step 2: Select Elements with querySelector
Create a new file called app.js in the same folder. The first thing your JavaScript needs to do is find the elements it will work with.
const billInput = document.querySelector("#bill");
const tipInput = document.querySelector("#tip");
const button = document.querySelector("#calculate");
const resultParagraph = document.querySelector("#result");document.querySelector() searches the page for an element that matches a CSS selector. The hash sign means "id," so the selector "#bill" finds the element with an id of "bill".
Store each element in a const variable because the element itself will not change. You will read from it and write to it, but you will never replace it with a different element.
Step 3: Listen for a Click Event
You want something to happen when the user clicks the Calculate button. JavaScript uses event listeners for this.
button.addEventListener("click", () => {
console.log("Button was clicked!");
});addEventListener takes two arguments: the event name and a function to run when the event happens. The arrow function is the code that runs on each click.
Save both files, open index.html in your browser, open the console, and click the button. You should see:
Button was clicked!If nothing happens, check that your script tag is at the bottom of the body and the file name matches exactly.
Step 4: Read Input Values
Now replace the console.log placeholder with code that reads what the user typed.
button.addEventListener("click", () => {
const billAmount = billInput.value;
const tipPercent = tipInput.value;
console.log("Bill:", billAmount);
console.log("Tip %:", tipPercent);
});The .value property reads whatever is currently typed inside an input box. These values are always strings, even when the user types numbers, so you will need to convert them before doing math.
Type 50 for the bill and 15 for the tip, click Calculate, and you should see:
Bill: 50
Tip %: 15Step 5: Calculate the Tip and Total
String values cannot be used in math directly, so the next step converts them to numbers and calculates the result. Here is the calculation on its own, with example numbers standing in for the input values:
const billAmount = Number("50");
const tipPercent = Number("15");
const tipAmount = billAmount * (tipPercent / 100);
const total = billAmount + tipAmount;
console.log(`Tip: $${tipAmount.toFixed(2)}`);The Number() call turns a text value into an actual number so it can be used in math. The toFixed(2) method then rounds the result to two decimal places and returns a display-ready string, which is why it works well for currency. Running this code prints the calculated tip:
Tip: $7.50Back in app.js, this calculation replaces the two console.log lines from Step 4, using the same input values you already read.
Step 6: Show the Result on the Page
Printing to the console is useful for debugging, but users do not see the console. Update the page instead by replacing the console.log calls with a line that writes into the result paragraph:
resultParagraph.textContent =
`Tip: $${tipAmount.toFixed(2)} | Total: $${total.toFixed(2)}`;The textContent property replaces the text inside an element. The result paragraph started out empty, and this line fills it with the calculated tip and total instead of only printing it to the console. Enter a bill of 80 and a tip of 20, click Calculate, and the page shows:
Tip: $16.00 | Total: $96.00The user sees the result directly on the page. No console needed.
Step 7: Handle Empty Inputs
What happens if the user clicks Calculate without entering numbers? Converting an empty string produces 0, and multiplying by 0 gives a result of 0, which is confusing but not broken. A better experience shows a clear message instead.
This guard clause pattern checks a condition first and exits early if something is missing:
function describeInputs(bill, tip) {
if (!bill || !tip) {
return "Please enter both values.";
}
return "Ready to calculate.";
}
console.log(describeInputs("", "15"));The if statement checks whether either value is falsy, which covers an empty string. When a value is missing, the function returns early instead of continuing, so the code below never runs. Calling it with an empty bill prints the warning message:
Please enter both values.The real app applies this same check inside the click handler before running the calculation, so it can stop early with return and skip the math entirely.
Step 8: The Complete Code
Here is the final app.js with everything together, starting with the element references from Step 2:
const billInput = document.querySelector("#bill");
const tipInput = document.querySelector("#tip");
const button = document.querySelector("#calculate");
const resultParagraph = document.querySelector("#result");The click handler combines every step you built: reading the values, converting them, checking for empty input, calculating, and updating the page.
button.addEventListener("click", () => {
const billAmount = Number(billInput.value);
const tipPercent = Number(tipInput.value);
if (!billInput.value || !tipInput.value) {
resultParagraph.textContent = "Please enter both values.";
return;
}
const tipAmount = billAmount * (tipPercent / 100);
const total = billAmount + tipAmount;
resultParagraph.textContent = `Tip: $${tipAmount.toFixed(2)} | Total: $${total.toFixed(2)}`;
});Together, these two pieces are the whole app. The table below maps each concept to where it appears:
| Concept | Where |
|---|---|
| Variables | Storing element references and calculated values |
| DOM selection | Finding elements on the page |
| Events | Responding to a button click |
| Type conversion | Turning input strings into numbers |
| Conditionals | Checking for empty inputs |
| Template literals | Building the result string |
| DOM update | Showing the result to the user |
What to Build Next
Now that you understand the pattern, try these variations on your own:
- Add a split feature. Add a third input for the number of people and show the per-person amount.
- Add a preset tip button. Add buttons for 15%, 18%, and 20% that auto-fill the tip input.
- Style it. Add CSS to make the calculator look clean. The JavaScript works the same regardless of styling.
Each variation uses the same core skills: select elements, listen for events, read values, do math, update the page.
If you want to understand the theory behind each concept, start with the JavaScript beginner's guide to programming for a structured learning path. If you are completely new and want to know what JavaScript is first, read our beginner introduction to JavaScript.
Rune AI
Key Insights
- JavaScript files connect to HTML using the <script> tag.
- Use const for values that do not change and let for values that do.
- Functions package code into reusable blocks.
- querySelector selects HTML elements. addEventListener responds to user actions.
- textContent updates what the user sees on the page.
Frequently Asked Questions
Do I need to know HTML to follow this tutorial?
Can I run these examples on my phone?
What should I learn after finishing this tutorial?
Conclusion
You have built a small interactive page that takes user input, runs a function, and updates the page. This is the core pattern behind every web application -- listen for user action, run some logic, update what the user sees. With variables, functions, and DOM manipulation under your belt, you are ready to explore each concept in more depth.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.