Types, operators & formatting

Numbers that make sense

Lesson 3 of 20 · 8 min · Module 1: Values & first steps

A value has a type, and its type changes what an operation means. Numbers can be calculated; strings can be joined.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Distinguish numbers from strings
  • Use arithmetic and string concatenation
  • Format a value without changing its numeric source

The idea

The expression 2 + 3 is 5, while "2" + "3" is "23". A number’s toFixed(2) method returns a string with two decimal places.

const price = 12.5;
console.log("EUR " + price.toFixed(2)); // EUR 12.50

01Keep calculation and presentation separate

Calculate using numbers first. Convert the result to display text only at the boundary where a person needs to read it. Formatting is a presentation step, not a new numeric type.

const subtotal = 5 * 3;
const label = subtotal.toFixed(2);
console.log(typeof subtotal, typeof label);
Output
number string

02Read a method call

In price.toFixed(2), price is the value, toFixed is the operation, and 2 is the requested number of decimal places. The method returns a new string; it does not replace price. The supplied function formatPrice(price) is a reusable recipe: calling formatPrice(12.5) gives price the value 12.5. Use return to send the formatted string back to that caller.

Your turn

Write formatPrice(price) to return a string starting with "EUR ", followed by the price with exactly two decimal places.

What the checks look for

  • Formats a decimal price
  • Keeps two decimal places for whole numbers
  • Handles zero
Try it in the editor →

Take this with you

Choose the right type for the operation, then format the result for display.

Learn JavaScript Foundations for free

20 short lessons with real code and instant checks.

See the whole course →