Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

Values, Types and the Rules of Coercion

Name the primitive types, predict what the operators do to them, and convert and compare values on purpose instead of by accident.

Contentsand lesson path

What you will learn

  • Write programs with variables, operators, conditionals and loops, predicting the result of type coercion and of strict vs loose equality.

01. Why it matters

The pages you built in the HTML and CSS skills were quiet: markup that means something, styles that arrange it. JavaScript is what makes them respond. It reads what the visitor typed, decides whether a value is acceptable, works out totals, and changes the page as a result. Every one of those steps handles values, and every value has a type.

JavaScript is friendlier than most languages about mixing types: it silently converts a value from one type to another when an operator asks for it. That behaviour has a name, coercion, and it is behind a whole family of classic bugs. The value of a form input is always a string, even for type="number", so a quantity of 3 arrives as the text "3", and "3" + 1 is "31". Nothing warns you.

By the end of this lesson you will be able to name the primitive types, predict what the common operators do with mixed types, convert values explicitly, and compare values with a rule you chose rather than one you remembered by accident.

02. A map of the values

Most values you handle are one of seven primitive types: string, number, boolean, undefined, null, bigint and symbol. Anything else is an object, including arrays, dates and functions. Two of the primitives name the absence of a value, and they mean different things: undefined is what a variable holds when it has been declared but never assigned, while null is a value your code sets deliberately to say "nothing here".

Declare names with const by default and let when the variable will be reassigned. const stops reassignment of the name, not change inside the object it points to. var still works but belongs to older code; write new code without it. The typeof operator reports a type as a string, with one famous quirk:

JavaScript · types-tour.js
const name = 'Ada';             // string
const year = 2026;              // number: one type for integers and decimals
const price = 4.5;              // number
let done;                       // undefined: declared, never assigned
const empty = null;             // null: deliberately no value
const big = 9007199254740993n;  // bigint: beyond Number.MAX_SAFE_INTEGER
const id = Symbol('id');        // symbol: unique, unguessable key

console.log(typeof name, typeof year, typeof price);
console.log(typeof done, typeof empty, typeof big, typeof id, typeof (() => 1));
console.log(9007199254740993 === 9007199254740992);
console.log(big === 9007199254740993n);
Expected output
string number number
undefined object bigint symbol function
true
true

typeof null says "object" although null is a primitive. It has been that way since 1995 and fixing it would break too much code, so you simply memorise it. There is one number type for integers and decimals alike, stored as a 64-bit float, and it is exact only up to Number.MAX_SAFE_INTEGER. The two huge numbers above differ by one, yet compare equal as numbers; the bigint version, with its n suffix, keeps the distinction.

03. When values change type

Coercion is not random; each operator follows a fixed preference. The + operator prefers strings: if either side is a string, the other is turned into text and the two are joined. The other arithmetic operators prefer numbers: strings that look like numbers are converted, and anything that cannot be converted cleanly becomes NaN ("not a number", a number-typed value that means "this calculation failed").

So the operator, not the values, decides the story. Read the next block by asking of each line: "what does this operator prefer?"

JavaScript · coerce-math.js
console.log(1 + '2');    // + joins when either side is a string
console.log('6' * '2');  // * only multiplies, so the strings become numbers
console.log('10' / 2);   // 5, same rule
console.log(1 + true);   // true becomes 1
console.log('' + null);  // joining turns anything into text
console.log('' + NaN);
Expected output
12
12
5
2
null
NaN

04. Converting on purpose

Because coercion is always available, you can make the conversion explicit and keep the implicit work out of your logic. Number(value) converts a whole string to a number and demands the entire string be numeric. parseInt(value, 10) reads leading digits and stops at the first character that cannot belong to the number. String(value) and Boolean(value) do what their names say. Explicit conversion is also documentation: a reader sees where the string from the form becomes a number.

JavaScript · explicit.js
const raw = '  42  ';
console.log(Number(raw));       // 42: whitespace is trimmed first
console.log(Number('12px'));    // NaN: the whole string must be numeric
console.log(parseInt('12px'));  // 12: reads leading digits, stops at 'px'
console.log(String(2048) + '!');
console.log(Boolean('false'));  // true: any non-empty string, even this one
console.log(Boolean(0), Boolean(0n), Boolean(''));
console.log(Boolean(null), Boolean(undefined), Boolean(NaN));
Expected output
42
NaN
12
2048!
true
false false false
false false false

The last lines of that output are worth pausing on: Boolean answers false for the standard falsy values: false, 0, -0, 0n (BigInt), "", null, undefined and NaN (plus the legacy browser object document.all), and true for everything else. "false" is a non-empty string, so it is truthy, and so is an empty array. Keep that list of falsy values in your head; the next section uses it.

The classic place to convert deliberately is the boundary where data enters your program. A form field, a URL query parameter and a text file all give you strings:

JavaScript · form-check.js
// An input's .value is always a string, even for type="number".
const quantity = '3';
console.log(quantity + 1);          // '31', not 4: the number was joined on
console.log(Number(quantity) + 1);  // 4: convert first, then do maths
Expected output
31
4

05. Truthiness and equality

A condition such as if (value) does not require a boolean: JavaScript coerces the value, using the falsy list from the last section (false, 0, -0, 0n, "", null, undefined, NaN). That is convenient for "is anything there?" checks, and a trap when 0 or "" are meaningful values rather than "missing". When emptiness and zero must be told apart, check explicitly.

For comparisons you have two operators. ===, strict equality, is false unless both the type and the value match. ==, loose equality, converts one or both sides first, which produces famous oddities. Use === as your default; the one accepted use of == is value == null, which is a shorthand for "is null or undefined". One more trap: NaN is not equal to anything, including itself, so test for it with Number.isNaN().

JavaScript · equality.js
console.log(1 === '1'); // different types: never equal
console.log(1 == '1');  // loose: one side is converted first
console.log(0 == '');   // true, and rarely what you want
console.log(Number.isNaN(NaN), Number.isNaN('nope'));
Expected output
false
true
true
true false

06. Check your understanding

Practice check · 3 questions

Predict, then convert

Each question asks you to predict what the code does before you would run it.

Q1. What does this log? console.log(typeof null, typeof undefined);
Q2. A legacy feed sends prices as text such as the string `"12px"`, and you want the number 12. Which expression gives it?
Q3. What does this log? console.log(Boolean('false'), Boolean([]), Boolean(0));
Practice only: not graded, not saved, not evidence.

07. Apply it

This skill builds towards an orders module that reads a JSON array and returns reports without mutating its input, so start collecting decisions you will need there:

  1. Write down, from memory, the standard falsy values (including 0n and -0). Then check against the lesson and note which ones surprised you.
  2. Take three fields a shop form might send (quantity, discount code, gift-wrap flag) and decide for each: which type should it become, and which explicit conversion does that?
  3. Write one line that checks "the discount code is present" in a way that still accepts the code "0" if a shop ever used it, and one line that accepts it only if it is a non-empty string. Say in a comment which behaviour you would ship.

Where those strings come from, and how forms hand them over, is the subject of the forms and validation skill later in the roadmap.

08. Review prompt

Without looking back: name the seven primitive types and say in one sentence how undefined differs from null. Then state the preference of + and of the other arithmetic operators, list the standard falsy values, and explain when Number(s) and parseInt(s, 10) disagree. Finally, say why NaN === NaN is false and what you use instead.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check