Back to Blog
Lesson 4 of the JavaScript: From Zero to Interactive Web Pages course
JavaScriptJuly 15, 20264 min read

Basic Arithmetic and Operators in JavaScript

Learn how to use arithmetic operators for math and string concatenation for dynamic text. Build the logic needed for your interactive dashboard.

javascriptprogrammingweb-developmentbeginnersmathstrings
Mathematical study scene with open book, graph paper, and pen for learning and homework.

Previously in this course, we covered Variables and Data Containers and explored Primitive Data Types. Now that you can store and identify data, it's time to actually do something with it. In this lesson, we’ll learn how to perform calculations and combine strings, which are essential skills for building the dynamic logic in our to-do and weather dashboard.

Performing Mathematical Operations

At its core, JavaScript provides the standard set of math operators you’d expect from any calculator. These are the building blocks of any application that processes user data.

The Standard Operators

JavaScript supports the following basic arithmetic operators:

OperatorNameExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division10 / 25
%Modulo (Remainder)10 % 31

The modulo operator (%) is often the most confusing for beginners. It returns the remainder after division. It’s incredibly useful in programming for tasks like checking if a number is even (e.g., number % 2 === 0).

Increment and Decrement

When building a to-do list, you'll often need to track counts—like how many tasks remain. Instead of writing count = count + 1, we use shorthand:

  • Increment (++): Adds 1 to the variable.
  • Decrement (--): Subtracts 1 from the variable.
JAVASCRIPT
let taskCount = 0;
taskCount++; // taskCount is now 1
taskCount--; // taskCount is now 0

String Concatenation

A collection of wooden letter tiles forming words on a rustic wooden surface. Ideal for word game concepts.

Data isn't always numeric. Often, you need to join text together, a process known as string concatenation. In JavaScript, we use the + operator to combine strings or to glue variables into a message.

JAVASCRIPT
let userName = "Alex";
let welcomeMessage = "Hello, " + userName + "!";
console.log(welcomeMessage); // Output: "Hello, Alex!"

When you combine a string with a number, JavaScript performs "type coercion." It automatically converts the number to a string so they can be joined together.

JAVASCRIPT
let tasksCompleted = 3;
console.log("You have " + tasksCompleted + " tasks left."); 
// Output: "You have 3 tasks left."

Worked Example: Calculating Dashboard Totals

Let's apply this to our running project. Imagine we are tracking daily task progress. We want to calculate the completion percentage and display a status message.

JAVASCRIPT
let totalTasks = 10;
let completedTasks = 3;

// Incrementing for a new task added
completedTasks++; 

// Simple math
let remainingTasks = totalTasks - completedTasks;

// Concatenation for the UI
let statusUpdate = "Progress: " + completedTasks + " of " + totalTasks + " tasks done.";

console.log(statusUpdate);
console.log("Remaining: " + remainingTasks);

Hands-on Exercise

Open your browser console and try the following:

  1. Create a variable called itemsInCart and set it to 5.
  2. Create a variable called pricePerItem and set it to 10.
  3. Calculate the totalCost by multiplying the two variables.
  4. Use console.log to print a message like: "The total cost is $50". (Hint: use concatenation).
  5. Increment itemsInCart by 1 and recalculate the totalCost.

Common Pitfalls

Close-up of a rusty sewer manhole cover in a grassy Boston park.

  • String vs. Number Math: If you have let a = "5" (a string) and let b = 5 (a number), a + b will result in "55" (concatenation), not 10. Always ensure your numbers are stored as number types when performing math.
  • Operator Precedence: Just like in school math, multiplication and division happen before addition and subtraction. Use parentheses () if you need to force a specific order: (2 + 2) * 3 equals 12, whereas 2 + 2 * 3 equals 8.
  • Order of Increment: Using ++ before or after a variable (++x vs x++) behaves differently in complex expressions. For now, keep it simple and use it on its own line.

FAQ

Q: Can I use - or * with strings? A: No. JavaScript will return NaN (Not a Number) if you try to subtract or multiply strings that don't represent numbers. The + operator is unique because it is overloaded to handle both math and concatenation.

Q: Why is it called "concatenation"? A: It comes from the Latin concatenare, meaning "to link together." Think of it like connecting links in a chain.

Q: Is there a better way to join strings? A: Yes, using "Template Literals" (backticks), which we will cover in a later lesson. They allow you to embed variables directly into strings without using +.

Recap

Wooden Scrabble tiles spelling 'RECAP' on a brown textured background. Text concept image.

You now have the tools to perform basic math and join text. You can use +, -, *, /, and % for calculations, ++ and -- for updates, and the + operator to bridge variables and strings. These operations are the foundation for the logic we will build into our dashboard's features.

Up next: Capturing User Input — we'll move from hard-coded variables to accepting input directly from the user.

Similar Posts