Skip to the workspace
Pebellslearn by building
Type Casting  ›  Lesson

Explicit Type Casting

Explicit Type Casting 12 min

javascript / Explicit Type Casting

Explore each scene at your own pace.

01 · Explicit Type Casting

Explicit Type Casting

Explicit Type Casting

Number, String and Boolean explicitly convert values using their defined rules. parseInt and parseFloat parse numeric prefixes and are not whole-input validators.

Conversion and validation are separate jobs.

See the mechanism

Walk through the modelExplicit Type CastingAuthored snapshots of the example; use Run below to test the code.
Number("12px")NaN
The entire string is not a valid numeric representation.
1 of 3

Follow one example

javascript

Number rejects "12px" as a complete numeric value and produces NaN. parseInt reads the leading integer and stops at p, producing 12. A nonempty string is truthy, so Boolean("false") is true; it does not read the word as a boolean command. Always make the input contract explicit, including whether blank text is permitted.

Predict, change and check

Predict: Will Number("") produce NaN, or does blank text have a conversion rule?

Test your explanation: Test Number("") and Number(" "). If your form forbids blanks, reject trimmed empty text before checking the resulting number.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Conversion does not validate a whole field

Number('12px') is NaN, while parseInt('12px', 10) extracts 12 from a valid numeric prefix. Neither behavior is universally right; choose it according to the input contract. Supply the intended radix when teaching parseInt and test the complete spelling if the whole field must be numeric.

String(value) produces text; Boolean(value) applies truthiness rules. Boolean('false') is true because that string is nonempty. Number.isFinite and Number.isNaN inspect number values without the broad coercion of the global predicates. Keep a valid zero distinct from a missing value.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.