liveBook · Manning

Data conversion

As explained in Math for Web Design

Type conversion is the transformation of a value from one data type into another.

Data conversion transforms a value from one data type into another. JavaScript performs some conversions automatically, but explicit conversion makes layout calculations, animation timing, and comparisons easier to predict. section 2.2.7 section 2.1.3

Choose conversion deliberately when values come from different sources:

  • Use Number(value), unary +, parseInt(), or parseFloat() when numeric input arrives as text. section 2.2.7
  • Remember that arithmetic operators do not all behave alike: multiplication coerces numeric strings, while + may concatenate them. section 2.2.7
  • Prefer strict equality (=== and !==), which compares both type and value without coercion. section 2.1.3
  • Use parentheses when combining conversions and calculations so precedence does not change the intended result. section 2.9

Converting input before a comparison

A prompt or DOM value is a string even when it contains digits. Convert it before comparing it with a number: let input = "100"; let width = 100; let numericInput = Number(input); console.log(numericInput === width); // true. Without conversion, input === width is false. section 2.1.3

The concatenation trap

If input is "20", input * 1.15 produces the numeric value 23, but input + tip combines the string and number as "2023". Convert first when calculating a total: let input = Number(prompt("Enter the restaurant bill amount:")); section 2.8

Table 2.3 JavaScript comparison operators

Operator

Name

Example

Result

==

Equal (loose)

"5" == 5

true

===

Equal (strict)

"5" === 5

false

!=

Not equal (loose)

"5" != 5

false

!==

Not equal (strict)

"5" !== 5

true

<

Less than

3 < 5

true

>

Greater than

4 > 5

false

<=

Less than or equal

4 <= 4

true

>=

Greater than or equal

5 >= 6

false

Compare loose and strict operators, including the different results for "5" == 5 and "5" === 5. section 2.1.3

How Math for Web Design covers it

How deep it goes
Explains automatic and explicit number conversion with operator examples, exercises, and common concatenation bugs.
Examples
Uses string-number comparisons, arithmetic with "5", conversion methods, and a restaurant-bill calculation.
What it assumes
Assumes basic JavaScript values, operators, and comparisons while teaching coercion behavior explicitly.
What you can do after
Diagnose conversion bugs and apply Number(), unary +, parseInt(), parseFloat(), and strict equality.
How it connects
Connects data conversion with comparison operators, operator precedence, string concatenation, and numeric input.

Also explained in

Compare how 21 books explain data conversion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Math for Web Design. The section links point to the parts of the book it draws on.