Skip to content
LumenaryAcademy
Foundations 55 min

Values, types and variables

Numbers, strings and the other primitives, let and const, and the conversions JavaScript makes behind your back.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

Why types matter even when you don't write them

In JavaScript you never write a type next to a variable. You write let total = 0 and later total = "none", and nothing stops you. That is what dynamically typed means: variables do not have types, values do, and the engine checks them only as each operation runs.

This makes small programs quick to write. It also means that when two values of different types meet, JavaScript has to decide what to do, and it usually decides to convert one of them rather than complain. "5" + 2 is "52"; "5" - 2 is 3. Knowing exactly when and how those conversions happen is the difference between a JavaScript programmer who is surprised by their code and one who is not.

This lesson covers how to name values (const and let), the kinds of value there are, the arithmetic and text operations you will use every day, and the conversion rules, with the simple habits professionals use to avoid them.

DefinitionsH

const, let, and the var you should leave behind

Definition— const and let

const name = value creates a binding that can never be reassigned. let name = value creates one that can. Both are block-scoped: they exist only inside the nearest pair of braces { ... } and only from the line where they are declared onward.

The professional habit is simple: use const by default, and let only for a variable you actually reassign, such as a counter or an accumulator. Most variables in good JavaScript are const, and a reader who sees let knows to look for the place it changes.

javascript
let count = 1;
count = count + 1;            // fine: let can be reassigned

const capital = "Accra";
try {
  capital = "Kumasi";         // not allowed: const cannot be reassigned
} catch (err) {
  console.log(`${err.name}: ${err.message}`);
}

const scores = [70, 85];
scores.push(92);              // allowed: the array itself can change
console.log(count, capital, scores);
text
TypeError: Assignment to constant variable.
2 Accra [ 70, 85, 92 ]

The try ... catch lets the program report the error and carry on; lesson seven covers it properly. Notice the last line: const stops you from making scores refer to a different array, but the array it refers to can still change. const protects the name, not the contents. (Object.freeze protects the contents; lesson five shows it.)

Before 2015, the only keyword was var. It is function-scoped rather than block-scoped, a var used before its declaration silently holds undefined, and a var in a loop is shared by every pass through the loop, which causes a classic bug you will meet in lesson four. You will read var in older code; do not write it in new code. Names follow the usual rules (letters, digits, _ and $, not starting with a digit), are case-sensitive, and are written in camelCase by convention: priceCents, isReady, maxRetries.

IntuitionH

The kinds of value

Every JavaScript value is either a primitive or an object. Primitives are simple, immutable values; objects are collections of properties, and arrays and functions are objects too. There are seven primitive types:

TypeExamplesNotes
number42, 3.75, -0.5, NaN, Infinityone type for integers and fractions: 64-bit floating point
bigint42n, 2n ** 64nwhole numbers of any size; a trailing n marks them
string"Lagos", 'Lagos', `Lagos`immutable text
booleantrue, false
undefinedundefined"no value has been given": a missing argument, a missing property
nullnull"deliberately empty", set by a programmer
symbolSymbol("id")a unique value, used as a property key that cannot clash

The typeof operator tells you a value's type, as a string:

javascript
// The kinds of JavaScript value, and what typeof says about each.
const examples = [
  42,                 // number
  3.75,               // number: there is no separate integer type
  2n ** 64n,          // bigint: integers of any size
  "Lagos",            // string
  true,               // boolean
  undefined,          // undefined: "no value here"
  null,               // null: "deliberately empty"
  Symbol("id"),       // symbol: a unique key
  { city: "Lagos" },  // object
  [1, 2, 3],          // arrays are objects
  (x) => x * 2,       // functions are objects too, but typeof says "function"
];

for (const value of examples) {
  const kind = typeof value;
  console.log(kind.padEnd(10), String(value));
}
text
number     42
number     3.75
bigint     18446744073709551616
string     Lagos
boolean    true
undefined  undefined
object     null
symbol     Symbol(id)
object     [object Object]
object     1,2,3
function   (x) => x * 2

Two lines deserve a comment. typeof null is "object": a bug from the very first implementation, kept ever since because fixing it would break existing pages. To test for null, write value === null. And typeof cannot tell an array from other objects; use Array.isArray(value) for that. String(value) converts any value to text, which is why the object prints as the unhelpful [object Object]; console.log given the object directly shows its contents instead.

Worked examplesH

Numbers: one type, and its edges

JavaScript's number is an IEEE 754 double-precision floating-point number, the same as a double in C or Java and a float in Python. That gives about 15–17 significant decimal digits, and it brings the same edge cases as in those languages, plus a few of JavaScript's own:

javascript
// Numbers are 64-bit floating point (IEEE 754 "doubles").
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);

// Money: count in the smallest unit (cents, paise, kobo) and format at the end.
const priceCents = 1999;
const quantity = 3;
console.log(`Total: ${(priceCents * quantity / 100).toFixed(2)}`);

// Integers are exact only up to 2 ** 53 - 1.
console.log(Number.MAX_SAFE_INTEGER);
console.log(2 ** 53 === 2 ** 53 + 1);
console.log(2n ** 53n === 2n ** 53n + 1n);

// Division never throws: it gives Infinity or NaN.
console.log(7 / 0, -7 / 0, 0 / 0);
console.log(NaN === NaN, Number.isNaN(0 / 0));

// Remainder keeps the sign of the left operand.
console.log(7 % 3, -7 % 3, ((-7 % 3) + 3) % 3);
console.log(Math.round(2.5), Math.round(-2.5), Math.trunc(-2.7), Math.floor(-2.7));
text
0.30000000000000004
false
true
Total: 59.97
9007199254740991
true
false
Infinity -Infinity NaN
false true
1 -1 2
3 -2 -2 -3

What to take from it:

  • Decimal fractions are approximations. 0.1 has no exact binary representation, so 0.1 + 0.2 is a hair above 0.3. Never compare computed fractions with ===; compare the difference with a small tolerance. For money, store whole numbers of the smallest unit and convert only for display, as the priceCents example does. (Number.EPSILON is the gap between 1 and the next double; it is a fine tolerance for numbers near 1, too small for large ones.)
  • Integers are exact up to Number.MAX_SAFE_INTEGER, about nine quadrillion. Beyond that, neighbouring integers collapse into each other, as 2 ** 53 === 2 ** 53 + 1 shows. IDs from databases and other systems can exceed this; keep them as strings or use BigInt, which is exact at any size. BigInt and number cannot be mixed in arithmetic (1n + 1 throws a TypeError), which forces you to convert on purpose with BigInt(x) or Number(x).
  • NaN ("not a number") is what invalid arithmetic produces, such as 0 / 0 or Number("abc"). It is the only value not equal to itself, so x === NaN is always false. Test with Number.isNaN(x).
  • % is remainder, not modulo. Its result has the sign of the left side, so -7 % 3 is -1. For a "clock" result in 0 .. n-1, use ((a % n) + n) % n. This is the modular arithmetic of Lumenary Math's remainders and modular arithmetic.
  • Math.round rounds halves up, towards positive infinity, so -2.5 becomes -2. Math.trunc drops the fraction; Math.floor rounds down.

The Math object holds the rest of the toolkit: Math.max, Math.min, Math.sqrt, Math.hypot, Math.PI and so on. 2 ** 10 is exponentiation. Long numbers may use underscores for readability: 1_000_000 is one million.

Worked examplesH

Strings

Strings are immutable sequences of text. Single and double quotes are equivalent (teams pick one and let a formatter enforce it); backticks make template literals, which can span lines and interpolate ${expression}. Methods never change a string in place: they return a new one.

javascript
const city = "  São Paulo  ";
const trimmed = city.trim();

console.log(trimmed.length, trimmed.toUpperCase());
console.log(trimmed.includes("Paulo"), trimmed.startsWith("Sã"));
console.log([trimmed.slice(0, 3), trimmed.slice(-5), trimmed.at(-1)]);
console.log("7".padStart(3, "0"), "ab".repeat(3));
console.log("2026-11-19".split("-"));
console.log("a-b-c".replaceAll("-", " / "));

// Strings are immutable: methods return new strings.
const word = "hello";
word.toUpperCase();
console.log(word);

// length counts UTF-16 code units, not the characters you see.
const hello = "👋🏽 hi";
console.log(hello.length, [...hello].length);
const graphemes = [...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(hello)];
console.log(graphemes.length);
text
9 SÃO PAULO
true true
[ 'São', 'Paulo', 'o' ]
007 ababab
[ '2026', '11', '19' ]
a / b / c
hello
7 5
4

slice(start, end) takes the characters from start up to but not including end; negative positions count from the end, and so does at(-1). The line word.toUpperCase(); computed "HELLO" and threw it away, which is a common beginner's slip: write const shout = word.toUpperCase().

The last three lines show a subtlety worth knowing early. JavaScript strings are sequences of UTF-16 code units. Most characters take one unit, but emoji and many rarer characters take two, and what a reader sees as one symbol may be several code points joined together (here a waving hand plus a skin-tone modifier). So "👋🏽 hi" has length 7, contains 5 code points (spreading a string with ... splits it by code point), and shows 4 visible characters, which Intl.Segmenter can count. Use length for storage and protocol limits; use a segmenter when you truly mean "characters a person sees", for example to truncate a username for display.

Comparing strings

The operators < and > work on strings, comparing them code unit by code unit. That is fine for checking that two IDs are in order, but it is not how people sort words: every capital letter comes before every lowercase one, so "Zebra" < "apple" is true, and digits are compared as text, so "10" < "9" is true as well (while 10 < 9, with numbers, is false). For text that people will read, use a.localeCompare(b, locale), which returns a negative number, zero or a positive number and knows each language's rules. The same letter can sort differently by language: "ä".localeCompare("z", "de") is -1, because German files ä beside a, while "ä".localeCompare("z", "sv") is 1, because Swedish puts ä after z.

ExplanationH

Conversions: explicit, implicit and equality

You can convert on purpose with String(x), Number(x), Boolean(x) and BigInt(x). The trouble starts when JavaScript converts implicitly, because an operator received a type it did not expect:

javascript
// Implicit conversion (coercion): what the operators do with mixed types.
console.log("5" + 2);       // + with a string concatenates
console.log("5" - 2);       // - only works on numbers, so "5" becomes 5
console.log("5" * "2");
console.log(true + 1);
console.log([1, 2] + [3]);
console.log(Number(""), Number("  42 "), Number("42px"), parseInt("42px", 10));

// Loose equality (==) converts; strict equality (===) never does.
console.log(0 == "", 0 == "0", "" == "0");
console.log(null == undefined, null === undefined);
console.log(0 === -0, Object.is(0, -0));

// Truthy and falsy values.
const values = [0, -0, 0n, "", null, undefined, NaN, false, "0", " ", [], {}];
console.log(values.filter((v) => !v).length, "falsy of", values.length);

// || picks the first truthy value; ?? only skips null and undefined.
const volume = 0;
console.log(volume || 50, volume ?? 50);
text
52
3
10
2
1,23
0 42 NaN 42
true true false
true false
true false
8 falsy of 12
50 0

The rules behind this output:

  • + prefers strings. If either side is a string (or an object, such as an array, which converts to a string), + concatenates. Every other arithmetic operator converts both sides to numbers. So "5" + 2 is "52" but "5" - 2 is 3, and [1, 2] + [3] joins "1,2" and "3".
  • Number is strict, parseInt is lenient. Number("42px") is NaN, while parseInt("42px", 10) reads digits until it hits something else. Number("") is 0, which surprises people who expected NaN. Always pass the radix (10) to parseInt.
  • == converts before comparing, by rules intricate enough that 0 == "" and 0 == "0" are both true while "" == "0" is false: equality that is not even transitive. === never converts: different types are simply unequal. Use === and !== everywhere. The one idiom some teams allow is x == null, which is true exactly for null and undefined.
  • Truthy and falsy. In an if or with !, every value counts as true except eight falsy values: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", " ", an empty array [] and an empty object.
  • ?? versus ||. a || b gives b whenever a is falsy, so a legitimate 0 or "" gets replaced. The nullish coalescing operator a ?? b gives b only when a is null or undefined. For default values, ?? is almost always what you mean.

Example— A settings bug, and its fix

A video player reads the saved volume with const volume = saved.volume || 50. A user who muted the player (volume 0) finds it at 50 every time they come back, because 0 is falsy. The fix is one character pair: saved.volume ?? 50. There is a matching assignment form too: settings.volume ??= 50 sets the property only if it is currently null or undefined.

What professionals do about all this is mostly habit, enforced by tools: === always (the ESLint rule eqeqeq), explicit Number(...) or String(...) at the boundary where data arrives from a form, a file or a network, ?? for defaults, and, in larger code bases, TypeScript, which catches most of these mixtures before the program runs (it has its own course in this series).

Common misconceptionsH

Common misconceptions

Misconception

"const makes a value constant." It makes the binding constant: the name cannot be pointed at something else. An object or array held in a const can still be changed. For data that must not change, use Object.freeze, or simply don't mutate it.

Misconception

"JavaScript can't do integer arithmetic." It can, exactly, for every integer up to 2 ** 53 - 1 in absolute value, which covers counts, indices and most IDs. Past that, BigInt is exact at any size. What JavaScript cannot do, like every language using binary floating point, is represent most decimal fractions exactly.

Misconception

"An empty array is falsy." It is truthy, like every object. To test for an empty array, check list.length === 0.

Misconception

"null and undefined are interchangeable." They behave alike in == and ??, but they signal different things: undefined is what the language gives you for something that was never set; null is what a programmer writes to say "empty on purpose". Many teams use undefined for "absent" in their own code and accept null where an API or JSON gives it, since JSON has null but no undefined.

Exercises

Exercises

Predict each answer before running anything; then check with node.

1. Values, types and variables

Warm-upComputational

What does this print?

console.log("3" + 4 + 5, 3 + 4 + "5");

2. Values, types and variables

Warm-upComputational

What does console.log(-17 % 5) print?

3. Values, types and variables

CoreComputational

What does this print?

const n = null;
console.log(n ?? "none", n || "none", 0 ?? "none", 0 || "none");

4. Values, types and variables

CoreComputational

Which of these values are falsy? Choose all that apply.

Choose all that apply

5. Values, types and variables

CoreComputational

What does this print?

console.log(typeof null, typeof [], typeof NaN);

6. Values, types and variables

CoreComputational

Which of these expressions evaluate to true? Choose all that apply.

Choose all that apply

7. Values, types and variables

StretchComputational

The flag of Kenya, 🇰🇪, is written in Unicode as two "regional indicator" symbols (for K and E), each outside the Basic Multilingual Plane. What does console.log("🇰🇪".length) print?

8. Values, types and variables

StretchHuman

A shop's checkout adds up prices like 19.99 and 4.10 and must never be off by a cent. Which approach do experienced JavaScript developers use?

Choose one

Further reading and resources