← Web basics: HTML, CSS and JavaScript

Numbers and text

Math, joining text, template strings, and turning text into numbers.

Start this lesson

JavaScript works with numbers (like 3 or 4.99) and strings (text in quotes, like "hello"). Numbers use + - * / for math, and % gives the remainder of a division. With strings, + joins them together. A template string, written in backticks, lets you drop values into text with a dollar sign and braces, like `Hi, ${name}!`. Watch out: anything typed into a web page arrives as a string, so "5" + 3 gives "53". Use Number("5") to turn text into a number first.

const price = 2.5;
const cups = 4;
const total = price * cups;           // 10
const label = "Total: " + total;       // "Total: 10"
const first = "Sam";
const hello = `Hello, ${first}!`;      // "Hello, Sam!"
const typed = "7";
const sum = Number(typed) + 3;         // 10, not "73"
const money = (19.5).toFixed(2);      // "19.50"

total is real math. label and hello build text. Number turns the string "7" into the number 7 before adding. toFixed(2) gives a string with exactly two decimals, handy for money.

Strings have useful tools: "hello".length is 5, "hello".toUpperCase() is "HELLO", and " hi ".trim() is "hi".

Computers store decimals in binary, so 0.1 + 0.2 gives 0.30000000000000004. Use toFixed when showing money.