LEARN TO CODE | JAVASCRIPT | 01 LANGUAGE FOUNDATIONS

01.3 Data types, operators and template literals

Recognise common value types, calculate deliberately and build readable messages without confusing text and numbers.

01 | 12 AND "12" ARE DIFFERENT VALUES

A website may show 12 remaining tickets. It may also receive the text "12" from a form. They look similar on screen, but the program does not treat them identically in every operation.

A data type describes the kind of value. A number supports numeric operations; a string holds text; a boolean expresses true or false. Understanding these differences prevents many early JavaScript bugs.

JavaScript is dynamically typed: you do not write a type annotation when declaring these variables, and a let binding can later hold a different type. That flexibility makes it especially useful to check what your values represent.

Keep index.html and script.js in the same VS Code folder. Put the current example into script.js, save it, open or refresh index.html in your browser and look in that page’s Developer Tools Console.

Replace the previous example unless a task explicitly says to add to it. Pasting several independent examples together can redeclare the same let or const name. The downloadable examples use a separate folder for each complete program.

02 | COMMON TYPES YOU WILL MEET

A practical starting set
Type Example Meaning
number 12 or 3.5 Ordinary numeric values, including whole and fractional numbers
string "Robotics" or "12" Text; quotes distinguish a string literal
boolean true or false A logical value, without quotes
undefined let result; No value has been assigned to this binding yet
null null An explicit value often used to represent an intentionally absent result

JavaScript has other types, including bigint, symbol and object. We introduce arrays and objects in the next section rather than trying to use every type at once.

JavaScript’s ordinary number type is used for both whole and fractional numbers. There is not a separate everyday int declaration in these examples.

03 | INSPECT WITH TYPEOF

const seats = 12;
const label = "12";
const isOpen = true;
let result;

console.log(typeof seats);
console.log(typeof label);
console.log(typeof isOpen);
console.log(typeof result);
console.log(typeof null);

typeof returns a string describing the type of its operand. The quotes around that returned string may or may not be shown by your logging interface.

typeof null returning "object" is a historical JavaScript quirk. null is not an ordinary object you should try to use that way. When checking whether a value is exactly null, use value === null.

04 | CALCULATE WITH ARITHMETIC

Numeric arithmetic
Operator Expression Result
+ 7 + 3 10
- 7 - 3 4
* 7 * 3 21
/ 7 / 2 3.5
% 7 % 2 1
** 2 ** 3 8

% gives the remainder. With non-negative whole numbers, 7 % 2 is 1 because dividing 7 into groups of 2 leaves 1. This is useful for checking whether an item number is even.

/ performs division, including fractional results. It does not mean integer division. ** means exponentiation: 2 ** 3 is 2 multiplied by itself three times.

const ticketPrice = 6;
const ticketCount = 3;
const deliveryCharge = 2;
console.log(ticketPrice * ticketCount + deliveryCharge);
console.log((ticketPrice + deliveryCharge) * ticketCount);

Multiplication happens before addition in the first calculation. Parentheses deliberately change the grouping in the second. These represent different pricing rules, so choose the one that matches the problem.

05 | PLUS CAN ALSO JOIN TEXT

console.log(5 + 2);
console.log("5" + "2");
console.log("5" + 2);
console.log("Total: " + 5 + 2);
console.log("Total: " + (5 + 2));

With these string/number operands, + joins text when a string is involved. The operation is called concatenation. "5" + 2 produces the string "52", not the number 7.

In "Total: " + 5 + 2, the joins happen left to right. The first join produces "Total: 5", then 2 is appended. Parentheses make 5 + 2 calculate before it is joined to the label.

Rather than relying on automatic conversion to guess what you meant, convert input deliberately and use readable message formatting.

06 | CONVERT TEXT DELIBERATELY

const quantityText = "12";
const quantity = Number(quantityText);
console.log(quantity + 3);
console.log(typeof quantity);

const badQuantity = Number("twelve");
console.log(Number.isNaN(badQuantity));
console.log(Number(""));
console.log(Number("   "));

Number converts text to a numeric value where possible. Text such as "twelve" produces NaN, meaning Not-a-Number. Use Number.isNaN(value) to test that result; do not test value === NaN.

Empty or whitespace-only strings convert to 0. That does not mean the visitor deliberately entered zero. In later form lessons, check for blank input separately before accepting the converted value.

Number.isFinite helps reject NaN and infinities; Number.isInteger can check whole-number requirements. Conversion alone is not complete validation of a quantity.

TRY IT YOURSELF

What is the difference between Number("8") + 2 and "8" + 2?

Reveal guidance

The first converts to the number 8, then calculates 10. The second joins text and produces "82".

07 | TRUE AND FALSE ARE NOT QUOTED

const score = 8;
console.log(score >= 5);
console.log(score === 10);
console.log(8 === "8");
console.log(8 !== "8");

A comparison produces a boolean in these examples. >= means greater than or equal to, and === checks strict equality without the loose equality operator’s type conversion.

Use === and !== as your default equality comparisons in this course. = assigns a value; === compares values. Confusing the two can change program state when you intended to ask a question.

"false" is a non-empty string, not the boolean false. That difference matters when it is used in a condition.

Comparison operators
Comparison Meaning
a < b a is less than b
a <= b a is less than or equal to b
a > b a is greater than b
a >= b a is greater than or equal to b
a === b Strict equality
a !== b Strict inequality

08 | BUILD MESSAGES WITH TEMPLATE LITERALS

const playerName = "Alex";
const wins = 3;
const pointsPerWin = 5;
console.log(`${playerName} has ${wins * pointsPerWin} points.`);

A template literal uses backticks, `, rather than ordinary single or double quote marks. ${...} marks an expression whose result should be inserted into the text. This insertion is called interpolation.

In this example, JavaScript reads playerName, calculates wins * pointsPerWin, converts the results for the message and builds one string. Punctuation and spaces outside the expressions stay as written.

Using ordinary quotes around "${playerName}" would print the placeholder characters rather than interpolate them. The backtick key position varies by keyboard, so check the character carefully.

TRY IT YOURSELF

Create a message saying “3 tickets cost 18 credits.” from const count = 3 and const price = 6.

Reveal guidance
const count = 3;
const price = 6;
console.log(`${count} tickets cost ${count * price} credits.`);

09 | PRECISION AND FORMATTING

Many decimal fractions cannot be represented exactly by JavaScript’s ordinary binary floating-point numbers. A result that looks surprising is not necessarily a problem with your addition algorithm.

console.log(0.1 + 0.2);
const total = 3 * 2.5;
console.log(total.toFixed(2));
console.log(typeof total.toFixed(2));

toFixed(2) produces a string formatted with two digits after the decimal point. It is useful for display, not a change to the underlying numeric representation.

For a small money-style exercise, storing whole cents can simplify arithmetic. Production financial calculations need deliberately chosen decimal/currency rules; do not assume formatting alone makes them exact.

10 | TRY THE TYPE EXPLORER

Choose a fixed expression, predict its value and type, then check. This activity never executes code entered by a visitor.

Do not judge a type only from its displayed characters. Logging typeof next to a value is often the quickest way to explain a confusing calculation.

11 | PUT THE IDEAS TOGETHER

const studentName = "Alex";
const quantityText = "3";
const ticketCount = Number(quantityText);
const priceInCents = 650;
const totalInCents = ticketCount * priceInCents;
const totalDisplay = (totalInCents / 100).toFixed(2);
console.log(`${studentName}: ${ticketCount} tickets cost ${totalDisplay}.`);

This fixed-data example converts the known numeric text, calculates using whole cents and formats a display string. It is not yet a public form: later lessons add checks before accepting user input.

TRY IT YOURSELF

Change quantityText to "4" and predict the output. Then explain why totalDisplay is a string.

Reveal guidance

The total display becomes 26.00. toFixed returns formatted text, so totalDisplay is a string even though it was derived from a number.

KEEP LEARNING

Previous page 01.4 Conditions and loops

Download Section 01 example programs

Further reading: JavaScript in VS Code · Grammar and types · Template literals · Loops and iteration