Learn by reading through in order

Type Conversion — Number / String / parseInt and Implicit Conversion

Turn input strings into numbers with explicit conversion, and see the implicit conversion operators trigger.

A quantity typed into an input field, or an amount buried in data from an external source. Even when these look the same on screen — both 1200 — whether JavaScript is holding it as a string or a number changes what a calculation does with it.

This article covers two things: explicit type conversion (changing a value's type yourself by calling something like Number), and implicit type conversion (operators automatically aligning types before they calculate).

Checking the Current Type — typeof

Aligning types starts with knowing what type something already is. Bugs like a total that's off, or a comparison that doesn't come out the way you expected, usually trace back to a value you assumed was a number turning out to be a string.

First, let's cover how to check a value's type on the spot.

Put typeof (an operator that returns a value's type name as a string) in front of a value, and you get its type. typeof 1200 is "number", and typeof "1200" is "string".

What comes back isn't the type itself — it's a string naming the type — so when you use it in a check, compare it against a quoted string, as in typeof price === "number".

What typeof Returns
typeof "A-1042"Returns the typename as a string"string"typeof 1200Check with=== "number""number"typeof trueNot the bareword string"boolean"
What comes back isn't the type itself — it's a string naming the type. Compare it against a quoted string when checking.
const orderId = "A-1042";   // order number

console.log(typeof orderId);   // string
console.log(typeof 500);       // number
console.log(typeof true);      // boolean

// Works on expression results too, not just variables
console.log(typeof (500 + 100));            // number
console.log(typeof (500 > 100));            // boolean
console.log(typeof `Order ${orderId}`);      // string

Check the types of 3 values coming from a product edit screen. inputPrice / stockCount / isPublished are already declared.

① Display the type of inputPrice.

② Display the type of stockCount.

③ Display the type of isPublished.

④ Check and display whether inputPrice is NOT the number type.

(If it runs correctly, an explanation will appear.)

JavaScript / TypeScript Editor

Run code to see output

Implicit Conversion — Only + Becomes String Concatenation

Calculate with values of different types, and JavaScript doesn't stop with an error. The operator aligns the types first, then just keeps going.

The same behavior you saw == do before comparing shows up in arithmetic operators too. Since it never stops, you won't notice the mismatch until you see the result.

The catch is that + makes a different call than the other operators. + chooses string concatenation if either side is a string. The number side gets converted to a string, so "3" + 1 becomes "31".

- * / %, on the other hand, have no meaning for joining strings together, so they convert the string side to a number and calculate.

If a total field shows two amounts sitting side by side, that's a sign they got added before being converted.

Different Operators Convert to Different Types
"3" + 1Joins asa string"31""3" - 1Converts toa number first2"3" * 2Converts toa number first6
Only + prioritizes string concatenation. The other arithmetic operators convert the string side to a number.
const inputQuantity = "3";   // value from the quantity input field (string)

// Display alone can't tell the number 31 apart from the string "31" — use typeof below
console.log(inputQuantity + 1);   // 31   joined as the string "31"
console.log(inputQuantity - 1);   // 2    converted to a number before subtracting
console.log(inputQuantity * 2);   // 6    multiplication converts too
console.log(inputQuantity / 3);   // 1    division converts too

// typeof confirms that only +'s result has a different type
console.log(typeof (inputQuantity + 1));   // string
console.log(typeof (inputQuantity - 1));   // number

Treat Values from Outside as Strings

Numbers from an input field, or buried in data from an external source, normally arrive as strings. If addition you meant as 1200 + 300 shows up as "1200300" side by side, that's a sign one side stayed a string. Convert it to a number before adding.

Explicit Conversion — Number / String / Boolean

Leaving conversion up to the operator means the direction it converts is fixed per operator, so your own intent doesn't show up in the code. Align types yourself before a calculation, and the result gets easier to follow.

JavaScript provides a conversion function for each type.

Number(value) converts to a number, String(value) to a string, and Boolean(value) to a boolean — each returns a new value. The original variable stays unchanged.

Boolean follows the falsy rules exactly: "" and 0 become false, and a non-empty string becomes true. Note that Number("") returns 0, not NaN, so converting a blank field straight to a number treats it as an amount of 0.

What the 3 Conversion Functions Return
Number("1200")string → number1200String(1200)number → string"1200"Boolean("")string → booleanfalse
All three return a new value — the variable you passed in stays the same.
const inputQuantity = "3";   // value from the quantity input field
const shippingFee = 500;     // shipping fee (number)

console.log(Number(inputQuantity));         // 3     string to number
console.log(Number(inputQuantity) + 1);     // 4     addition works as a number now
console.log(String(shippingFee));           // 500   number to string
console.log(typeof String(shippingFee));    // string

console.log(Boolean("Tokyo"));   // true    a non-empty string
console.log(Boolean(""));        // false   an empty string is falsy
console.log(Number(""));         // 0       an empty string becomes 0

// The original variable stays a string even after converting
console.log(typeof inputQuantity);   // string

Work out a cart subtotal from a quantity that came from an input field and a unit price. inputQuantity / unitPrice / inputCoupon are already declared.

① Display the result of converting inputQuantity to a number.

② Work out and display the subtotal from ①'s number and unitPrice.

③ Display the type you get from converting ②'s subtotal to a string.

④ Display the result of converting the blank coupon field, inputCoupon, to a boolean.

JavaScript / TypeScript Editor

Run code to see output

Failed Conversions — NaN and Number.isNaN

Pass Number a string it can't turn into a number, and JavaScript doesn't throw an error. Instead it returns NaN (a value meaning the result couldn't become a number) and just moves on to the next calculation.

That's why an amount field with a full-width character or a comma mixed in can leave a total sitting as NaN all the way to the screen. After converting, you need to check for yourself whether it actually worked.

Writing total === NaN doesn't work as a check here. NaN doesn't even equal itself, so the result is always false.

typeof NaN also returns "number", so type doesn't distinguish it either. Use Number.isNaN (a function that returns whether the value passed to it is NaN) for the check instead.

const inputAmount = "1,200";   // an amount typed in with a comma

console.log(Number(inputAmount));         // NaN   a comma can't be converted
console.log(Number(inputAmount) + 500);   // NaN   a calculation after that stays NaN too

// Neither comparison nor type can tell it apart
console.log(Number(inputAmount) === NaN);   // false
console.log(typeof NaN);                    // number

// Use the dedicated function to check
console.log(Number.isNaN(Number(inputAmount)));   // true

Check whether a value typed into an amount field can be treated as a number, and show a message only when it can't. inputAmount / validAmount are already declared.

① Display the result of converting inputAmount to a number.

② Check and display whether ①'s result is a failed conversion.

③ Run the same check on validAmount and display the result.

④ Only when inputAmount's conversion has failed, display "Please enter the amount as a number."

JavaScript / TypeScript Editor

Run code to see output

Reading a String That Starts With a Number — parseInt and parseFloat

Sometimes you're handed a string like "240px" or "12.5%" — digits followed by a unit. Number reads the entire string as a number, so leftover unit text turns the result into NaN.

When you just want the leading digits, use a different function.

parseInt (a function that pulls out however much from the start can be read as an integer) gets 240 out of "240px". The 10 you pass as the second argument means "read it using the usual base-10 digits, 0 through 9." You can leave it off, but writing it makes your intent clear to anyone reading it.

When you want to read as far as the decimal point too, use parseFloat (a function that pulls out however much from the start can be read as a decimal). Both return NaN if there's nothing readable as a number right at the start.

How Number Differs from parseInt / parseFloat
Number("240px")Tries to read thewhole thingNaNparseInt("240px")From the start,as an integer240parseFloat("12.5%")From the start,as a decimal12.5
Number looks at the entire string. parseInt and parseFloat only pull out however much is readable from the start, differing in whether they read as far as the decimal point.
const cardWidth = "240px";   // width read from a style value

console.log(Number(cardWidth));         // NaN    can't convert the whole thing
console.log(parseInt(cardWidth, 10));   // 240    only what's readable from the start

console.log(parseFloat("12.5%"));       // 12.5   reads as far as the decimal point
console.log(parseInt("12.5%", 10));     // 12     reading as an integer drops the decimal

// Nothing is read if it doesn't start with a digit
console.log(parseInt("about 240px", 10));   // NaN

Reading Only the Start Can Hide a Silent Truncation

parseInt stops the moment it can't read any further. The comma-separated "1,200" becomes 1, and "12.5" becomes 12. Neither errors out, so use Number for values like an amount where you need to read the whole thing, and save parseInt for strings with a unit attached.

Pull just the numeric part out of a style value and a display string. cardWidth / discountText are already declared.

① Display the result of converting cardWidth to a number as a whole string.

② Pull the numeric part out of cardWidth as an integer and display it.

③ Pull the numeric part out of discountText as a decimal and display it.

④ Display ②'s value doubled.

JavaScript / TypeScript Editor

Run code to see output
QUIZ

Knowledge Check

Answer each question one by one.

Q1What does running console.log("5" + 1); display?

Q2What's the result of console.log(Number("240px"));?

Q3Which of these correctly checks whether a converted result is NaN?