Numbers, strings and operators
Do maths in JavaScript with arithmetic operators and Math, round money correctly, use string methods like trim, includes and slice, and avoid the classic "2" + "3" = "23" trap.
🎯 By the end of this lesson you will be able to:
- Calculate with arithmetic operators, Math.round and toFixed
- Use common string properties and methods
- Convert text to numbers safely with Number()
Outline
What you'll learn and why it matters
Most programs work with numbers and text: prices, totals, names, messages, search terms. In this lesson you will calculate, round money properly, clean up text people type, and learn the conversion rule behind one of JavaScript's most famous surprises.
Arithmetic
console.log(10 + 3);
console.log(10 - 3);
console.log(10 * 3);
console.log(10 / 3);
console.log(10 % 3);
console.log(2 ** 3);Console (Chrome and Edge)
13 7 30 3.3333333333333335 1 8
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * / | Add, subtract, multiply, divide | 10 / 4 | 2.5 |
% | Remainder after dividing | 10 % 3 | 1 |
** | Power | 2 ** 3 | 8 |
The usual maths order applies: * and / before + and -. Use brackets to make your meaning clear: (price + delivery) * 2.
Changing a variable: shortcuts
let total = 100;
total += 50;
console.log(total);
total -= 20;
console.log(total);
total *= 2;
console.log(total);
let count = 0;
count++;
count++;
console.log(count);Console (Chrome and Edge)
150 130 260 2
total += 50 is short for total = total + 50. count++ adds 1.
Rounding and money
Computers store decimals in binary, so some answers come out very slightly off:
console.log(0.1 + 0.2);Console (Chrome and Edge)
0.30000000000000004
This happens in almost every programming language. For display, round the result:
const price = 19.99;
const quantity = 3;
const total = price * quantity;
console.log(total);
console.log(Math.round(total));
console.log(total.toFixed(2));
console.log(Math.floor(4.8));
console.log(Math.ceil(4.2));Console (Chrome and Edge)
59.97 60 59.97 4 5
| Code | Does |
|---|---|
Math.round(x) | Rounds to the nearest whole number |
Math.floor(x) / Math.ceil(x) | Rounds down / up |
x.toFixed(2) | Text with exactly 2 decimal places, ideal for prices |
Math.max(a, b) / Math.min(a, b) | The larger / smaller value |
Math.random() | A random decimal from 0 up to (not including) 1 |
Working with strings
Strings have a length and many built-in methods: actions written after a dot, with brackets.
const typed = " Masala Chai ";
const clean = typed.trim();
console.log(clean);
console.log(clean.length);
console.log(clean.toUpperCase());
console.log(clean.toLowerCase());
console.log(clean.includes("Chai"));
console.log(clean.startsWith("Mas"));
console.log(clean.slice(0, 6));
console.log(clean.replace("Chai", "Tea"));Console (Chrome and Edge)
Masala Chai 11 MASALA CHAI masala chai true true Masala Masala Tea
| Method | Returns |
|---|---|
.trim() | The string without spaces at the start and end |
.toUpperCase() / .toLowerCase() | The string in capitals / small letters |
.includes(text) | true if the text appears in the string |
.startsWith(text) | true if the string begins with the text |
.slice(start, end) | Characters from start up to (not including) end; positions start at 0 |
.replace(a, b) | A new string with the first a replaced by b |
String methods never change the original string; they give you a new one. That is why we store the result: const clean = typed.trim();.
Numbers and text: the + trap
+ means *add* for numbers but *join* for strings. If either side is a string, JavaScript joins:
console.log(2 + 3);
console.log("2" + "3");
console.log("2" + 3);
console.log("6" * 2);Console (Chrome and Edge)
5 23 23 12
This matters because everything people type into a web page arrives as a string, even numbers. Convert first with Number():
const typedQuantity = "3";
const typedPrice = "40";
console.log(typedQuantity + typedPrice);
console.log(Number(typedQuantity) * Number(typedPrice));
console.log(Number("hello"));Console (Chrome and Edge)
340 120 NaN
Practice
Guided exercise
A bill splitter
Three friends share a bill of 1,250. Add a 10% tip, then work out each person's share to 2 decimal places.
- Store
bill = 1250,tipPercent = 10andpeople = 3. - Work out
tip = bill * tipPercent / 100andtotal = bill + tip. - Divide by
peopleand use.toFixed(2)when printing.
Show the solution
const bill = 1250;
const tipPercent = 10;
const people = 3;
const tip = bill * tipPercent / 100;
const total = bill + tip;
const share = total / people;
console.log(`Tip: ${tip}`);
console.log(`Total: ${total}`);
console.log(`Each pays: ${share.toFixed(2)}`);Console (Chrome and Edge)
Tip: 125 Total: 1375 Each pays: 458.33
How to get there: Work in small, named steps so each value can be checked. 1375 / 3 is 458.333…, and toFixed(2) gives the text 458.33 for display.
Your turn
Tidy a username
Someone typed " RaviK_2026 " as a username. Print it trimmed and in lower case, print its length, and print whether it includes "2026".
Show the solution
const typed = " RaviK_2026 ";
const username = typed.trim().toLowerCase();
console.log(username);
console.log(username.length);
console.log(username.includes("2026"));Console (Chrome and Edge)
ravik_2026 10 true
How to get there: Methods can be chained: trim() returns a new string, and .toLowerCase() is called on that. The length is counted after trimming, so the spaces do not count.
Common mistakes
Adding numbers that came from a form
You see: "3" + "40" gives "340"
Fix: Convert with Number() before doing maths.
Expecting toFixed to return a number
You see: Later maths joins text, e.g. "5.00" + 1 gives "5.001"
Fix: Keep numbers for maths; use toFixed only when displaying.
Expecting a string method to change the original
You see: The variable still has spaces or capitals
Fix: Store the result: name = name.trim(); or use a new variable.
Forgetting the brackets on a method
You see: The console shows ƒ toUpperCase() { [native code] } instead of text
Fix: Methods are called with brackets: .toUpperCase().
Recap
- Arithmetic:
+ - * / % **; use brackets to make order clear;+=and++update variables. - Decimals can be slightly off; round with
Math.roundor display money withtoFixed(2). - Strings have
lengthand methods such astrim,toLowerCase,includes,sliceandreplace. +joins if either side is a string; convert typed values withNumber()and watch forNaN.
Key terms
- Operator
- A symbol that does something with values, such as + or %.
- Method
- A built-in action on a value, called with a dot and brackets, like name.trim().
- NaN
- Not a Number: the result of a maths operation that has no numeric answer.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. What does `console.log("5" + 5)` print?
2. What is `17 % 5`?
3. Which shows a price of 7.5 as "7.50"?
4. What does `" Hi ".trim().length` give?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.