Make Math Happen Instantly
Learn how to perform calculations and display results in real time.
Your browser can be a calculator, too. In this lesson, you’ll learn how to do math with JavaScript—and display the result instantly.
Goals
You’ll learn to:
Write math expressions in JavaScript.
Display the result using
console.log()
or HTML.Understand the basic math operators.
Let’s do some math
You can use JavaScript to quickly calculate values.
The +
adds numbers. You can also subtract, multiply, and divide:
Displaying the result on the page
Instead of logging to the console, you can show your result right on the webpage. Let’s say your HTML has the following element:
You can update that element with JavaScript like this:
You just made the page calculate and show the result. That’s real-time math!
Use variables to store numbers
To make our math cleaner and reusable, we can store values in variables. Think of a variable like a label for a box. We can store something inside, and later, we can use it again.
Let’s look at an example below that has three variables a
, b
, and sum
.
You can plug these into your page too:
This keeps your code flexible—you can easily change a
and b
without rewriting everything.
When you run the code above, you’ll see two panels:
On the left, the “Output” panel shows what the user would see on a real web page—here, it's showing the result of
a * b
inside the paragraph.On the right, the “Console” panel displays messages sent using
console.log()
—in this case, the sum ofa + b
. This is mainly used by developers to check or to find and correct errors while writing code.
The “Output” is what your users will see on your web page. The “Console” is what you (the coder) see behind the scenes, like a note to yourself.
You’re thinking like a coder now—breaking things into parts and reusing values.
Mini challenge
Let’s calculate a restaurant tip—just like the ones you’ve seen on food delivery apps! Create a simple tip calculator. The HTML is already set up for you, assuming a $100 bill and a 15% tip.
Use JavaScript to fetch the bill and tip percentage from the page, calculate the tip, and display it using the <p id="result">
element.
If you’re stuck, click the “Show Solution” button.
Try different percentages and bill values!
You just leveled up from console basics to building math-powered web pages.
Bonus: Operator quick list
+
Add-
Subtract*
Multiply/
Divide%
Modulo (remainder)
What’s next?
Next, let’s make math interactive—you’ll build a button that responds when clicked!