JavaScript Data Types and Coercion: Beginner Tutorial with Runnable Examples

Learn how JavaScript stores values, copies primitives and objects, converts input, compares values and produces surprising output. Trace each rule in the console.

KnowledgeGate Team

Exam prep & CS education

Updated 27 Sep 20265 min read

You can declare a JavaScript variable, yet still wonder why "5" + 2 gives "52", "5" - 2 gives 3, and Boolean("false") gives true. Browser inputs often arrive as strings, so unnoticed conversion can corrupt a total or flip a condition without a syntax error. The key rules concern primitive values, object references, explicit conversion, operators and equality. A traced study-time calculation shows how the same inputs produce either the string "452" or the number 90.

JavaScript's Value Types: The Map Before the Rules

JavaScript has eight language-level type categories. Seven are primitives: string, number, bigint, boolean, undefined, symbol and null. The eighth is object. Sample values are "KG", 42, 42n, true, undefined, Symbol("id"), null and { topic: "JS" }. Arrays and functions are specialised objects, although typeof function () {} returns "function".

javascript
console.log(typeof "KG");          // "string"
console.log(typeof 42);            // "number"
console.log(typeof 42n);           // "bigint"
console.log(typeof true);          // "boolean"
console.log(typeof undefined);     // "undefined"
console.log(typeof Symbol("id"));  // "symbol"
console.log(typeof null);          // "object"
console.log(typeof []);            // "object"

typeof null === "object" is a historical language quirk. Test null with value === null, not with typeof.

Tree diagram splitting JavaScript values into seven primitives and object, with notes on typeof null and functions being objects.

Primitives, Objects and What Assignment Copies

Assignment copies a primitive value. Reassigning the copy leaves the first variable unchanged.

javascript
let first = 7;
let second = first;
second = 9;
console.log(`first=${first}, second=${second}`); // first=7, second=9

Object variables, including arrays, can refer to the same mutable object:

javascript
const topics = ["types"];
const sameTopics = topics;
sameTopics.push("coercion");

console.log(topics);                              // ["types", "coercion"]
console.log(topics === sameTopics);               // true
console.log(topics === ["types", "coercion"]); // false
topics.push("equality");                       // allowed

The second array literal creates a different object, so equality is false. const prevents rebinding topics; it does not make the array immutable. Freezing or copying it is separate. This section establishes the primitive-versus-reference assignment rule. The earlier Objects in JavaScript: Beginner Tutorial with Runnable Examples develops property operations, aliasing and shallow copies.

Explicit Conversion: Number, String and Boolean

Explicit conversion makes the intended type visible.

Expression

Result

Reason

Number("42")

42

The complete string is numeric

Number("42px")

NaN

The complete string is not numeric

Number("")

0

An empty string converts to zero

String(false)

"false"

The boolean becomes text

Boolean("")

false

An empty string is falsy

Boolean("false")

true

A non-empty string is truthy

Boolean(0)

false

Zero is falsy

Boolean([])

true

Arrays are objects, and objects are truthy

The falsy primitive values are exactly false, 0, -0, 0n, "", null, undefined and NaN. Browsers also retain the legacy host object document.all as a special falsy exception. Other objects and arrays are truthy, including [] and {}.

javascript
console.log(Number.isNaN(Number("42px"))); // true
console.log(Number.parseInt("42px", 10));  // 42

Prefix parsing with parseInt should be deliberate. It is not a substitute for validating an entire numeric input.

Implicit Coercion and the + Operator: A Worked Study Tracker

The + operator can add or concatenate, creating a common input bug.

javascript
const minutesInput = "45";
const sessionCountInput = "2";
const breakInput = null;

const wrongTotal = minutesInput + sessionCountInput;
const minutes = Number(minutesInput);
const sessionCount = Number(sessionCountInput);
const studyMinutes = minutes * sessionCount;
const breakMinutes = breakInput === null ? 0 : Number(breakInput);
const totalMinutes = studyMinutes + breakMinutes;

console.log(wrongTotal, typeof wrongTotal); // "452" "string"
console.log(totalMinutes, typeof totalMinutes); // 90 "number"

Both inputs are strings, so "45" + "2" concatenates to "452", a string. Conversion produces 45 and 2. Multiplication gives 45 * 2 = 90. The null branch makes breakMinutes equal 0. Numeric addition gives 90 + 0 = 90, a number.

If sessionCountInput is "two", then Number("two") becomes NaN. Reject it with Number.isNaN(sessionCount) before calculating.

Other operators show why guessing is risky:

Expression

Result

Trace

"5" + 2

"52"

+ concatenates after a string is involved

"5" - 2

3

- converts "5" to 5

1 + true

2

true converts to 1

null + 1

1

null converts to 0

undefined + 1

NaN

undefined becomes NaN numerically

10n + 2n

12n

Both operands are BigInt

10n + 2 throws a TypeError. Do not mix BigInt and Number arithmetic.

Flow diagram contrasting "45" + "2" giving the string "452" with the Number path reaching totalMinutes 90, plus a NaN rejection branch.

Loose Equality, Strict Equality and Object.is

Strict equality, ===, does not coerce types. Loose equality, ==, follows rules that are easy to misread.

Expression

Result

0 == false

true

"0" == false

true

0 === false

false

null == undefined

true

null === undefined

false

NaN === NaN

false

Object.is(NaN, NaN)

true

Default to === and !==. Convert at the boundary when input should be numeric or boolean. value == null deliberately checks for either null or undefined, but is not the default style. After tracker conversion, compare sessionCount === 2, not sessionCount == "2".

Common Coercion Errors and Direct Fixes

Symptom

Why it happens

Exact example

Fix

A total becomes text

+ sees a string

"45" + 2 -> "452"

Validate, then call Number

A false-looking string passes a condition

Non-empty strings are truthy

Boolean("false") -> true

Parse the allowed text explicitly

A null check fails

typeof null is the historical quirk

typeof null -> "object"

Use value === null

A calculation becomes NaN

Invalid numeric text was converted

Number("7x") -> NaN

Reject with Number.isNaN

Objects can produce surprising primitives. String([]) gives "", so [] + 1 gives "1". String([1]) gives "1", so [1] + 1 gives "11". These are boundary examples, not production patterns. Normalise and validate inputs, then keep calculations on one intended type.

Output-Based Questions and Four Checks

Trace consistently: annotate each literal's type, evaluate parentheses, apply the operator's conversion rule, then record the intermediate value and type before moving right.

  1. console.log("10" + 5 - 3) prints 102. First, "10" + 5 gives "105"; subtraction converts it to 105, then calculates 105 - 3 = 102.

  2. console.log(Boolean("0"), Boolean(0)) prints true false. The first value is a non-empty string; the second is numeric zero.

  3. console.log(null == undefined, null === undefined) prints true false. Loose equality has a special match here; strict equality keeps the types distinct.

  4. console.log(Number(""), Number("7x")) prints 0 NaN. The empty string converts to zero; invalid numeric text becomes NaN.

For a cross-language comparison, try Python Output-Based Questions. Each language has its own conversion rules, but disciplined tracing works across them.

JavaScript Data Types and Coercion: Short Version and Next Step

Keep five rules:

  1. Know whether a value is a primitive or an object.

  2. Treat browser input as untrusted text.

  3. Convert explicitly at boundaries.

  4. Validate NaN and null before calculation.

  5. Prefer strict equality.

Run the study-time example. Change "45" to "45.5", then change "2" to "two". Predict every value and type before rerunning it.

Continue with the Complete JavaScript Course for the immediate language path. After the basics, the MERN Stack Course is a later full-stack path. Browse the Coding & Skills category for the broader course hub.