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.

7 min read

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.

Tip calculator app flow

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:

htmlhtml
<!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.

htmlhtml
<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.

javascriptjavascript
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.

javascriptjavascript
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:

texttext
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.

javascriptjavascript
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:

texttext
Bill: 50
Tip %: 15

Step 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:

javascriptjavascript
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:

texttext
Tip: $7.50

Back 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:

javascriptjavascript
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:

texttext
Tip: $16.00 | Total: $96.00

The 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:

javascriptjavascript
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:

texttext
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:

javascriptjavascript
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.

javascriptjavascript
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:

ConceptWhere
VariablesStoring element references and calculated values
DOM selectionFinding elements on the page
EventsResponding to a button click
Type conversionTurning input strings into numbers
ConditionalsChecking for empty inputs
Template literalsBuilding the result string
DOM updateShowing 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

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.
RunePowered by Rune AI

Frequently Asked Questions

Do I need to know HTML to follow this tutorial?

You need a basic understanding of HTML tags like &lt;h1&gt;, &lt;p&gt;, and &lt;button&gt;. If you can create a simple HTML page with headings and buttons, you are ready for this tutorial.

Can I run these examples on my phone?

Most mobile browsers do not have a built-in code editor. You will get the best experience on a laptop or desktop computer with Chrome, Firefox, or Edge.

What should I learn after finishing this tutorial?

Next, learn about variables and data types in more depth, then move on to arrays, loops, and how to fetch data from APIs.

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.