JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 2: Variables, Values and TypesLesson 10 of 150About 45 minutes

Lesson 10: Type conversion and type checking

01Opening question

Everything a user types into a web form arrives as text. How does "25" become the number 25 you can calculate with?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Text plus a number joins text. Convert first with Number() to calculate.

const typed = "25";
console.log(typed + 5);
console.log(Number(typed) + 5);
console.log(typeof typed, typeof Number(typed));

03Objective and prerequisites

Learning objective: Check types with typeof, convert explicitly with Number, String and Boolean, parse with parseInt and parseFloat, and predict implicit conversions.

You need: Lesson 7: Strings and template literals, Lesson 8: Numbers and mathematical operations, Lesson 9: Booleans, null and undefined

Skills practised: Values and variables, Type conversion.

04Explanation

typeof tells you a value's type: "number", "string", "boolean", "undefined", "object" (also for null and arrays) or "function".

Convert on purpose: Number("25") is 25, String(25) is "25", Boolean("") is false. When text is not a valid number, Number gives NaN.

parseInt("42px") reads digits from the start and stops at the first non-digit, giving 42. parseFloat("3.5kg") gives 3.5. Number("42px") would be NaN, because Number needs the whole text to be a number.

JavaScript also converts implicitly: "5" * 2 is 10, but "5" + 2 is "52" because + prefers joining text. Explicit conversion makes your intention clear and avoids surprises.

05Definitions

typeof
An operator that returns the type name of a value as a string.
Type conversion
Changing a value from one type to another, such as text to number.
Implicit coercion
A conversion JavaScript performs automatically, such as "5" * 2 → 10.
parseInt / parseFloat
Read a whole number / decimal from the start of a string.
Number()
Converts a value to a number, or NaN if the whole value is not numeric.

Open the full glossary

06Visual learning object

Type conversion explorer. Type any value and compare Number, parseInt, parseFloat, String, Boolean and unary + side by side.

Loading the interactive object…

Open the full Type conversion explorer page with its guided experiment.

07Examples

ex-010-01typeof every kind of value Browser-executable JavaScript

typeof returns a string naming the type. Note the two quirks: null and arrays are "object".

console.log(typeof 42);
console.log(typeof "42");
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof null);
console.log(typeof [1, 2]);
console.log(Array.isArray([1, 2]));
Sample input
None
Expected output
number string boolean undefined object object true
Common mistake
Using typeof to detect arrays.
Try this
Print typeof for a template literal and for NaN.
Source
examples/ex-010-01-typeof-everything.js (repository pending publication)

ex-010-02Explicit conversion Browser-executable JavaScript

Number, String and Boolean convert on purpose.

console.log(Number("25") + 5);
console.log(Number("12.5"));
console.log(Number("abc"));
console.log(Number(""));
console.log(String(99) + "!");
console.log(Boolean("yes"), Boolean(0));
Sample input
None
Expected output
30 12.5 NaN 0 99! true false
Common mistake
Forgetting that Number("") is 0, so an empty field looks like a valid number.
Try this
Convert " 7 " with Number. Are spaces allowed?
Source
examples/ex-010-02-explicit-conversion.js (repository pending publication)

ex-010-03parseInt and parseFloat Browser-executable JavaScript

The parse functions read a number from the start of text and stop at the first character that does not fit.

console.log(parseInt("42px", 10));
console.log(parseFloat("3.75kg"));
console.log(parseInt("3.75", 10));
console.log(Number("42px"));
console.log(parseInt("px42", 10));
Sample input
None
Expected output
42 3.75 3 NaN NaN
Common mistake
Using parseInt for prices and losing the cents.
Try this
Read the number from "Size: 10". Why does parseInt fail?
Source
examples/ex-010-03-parse-functions.js (repository pending publication)

ex-010-04Implicit coercion Browser-executable JavaScript

Arithmetic operators other than + convert text to numbers; + joins if either side is text.

console.log("6" * "2");
console.log("6" - 2);
console.log("6" + 2);
console.log(true + 1);
console.log("3" * "abc");
Sample input
None
Expected output
12 4 62 2 NaN
Common mistake
Relying on implicit conversion where a reader cannot tell what was intended.
Try this
Rewrite line 3 so it prints 8.
Source
examples/ex-010-04-implicit-coercion.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the form total

Convert text input before calculating.

// Values from two form fields always arrive as strings.
const adults = "2";
const children = "3";
const tickets = adults + children;
console.log("Tickets:", tickets);

Read the measurements

Choose parseInt or parseFloat for text with units.

const widthText = "120cm";
const weightText = "2.5kg";
// TODO: width = the whole number from widthText
const width = widthText;
// TODO: weight = the decimal number from weightText
const weight = weightText;
console.log(`Width ${width}, weight ${weight}`);
console.log(typeof width, typeof weight);

Validate an age field

Convert, then check for NaN and empty input.

const inputs = ["34", "", "abc", "17"];
// For each input, print one line as described in the instructions.

09Prediction

Commit to an answer first, then run the real code to compare.

console.log("10" - 4);
console.log("10" + 4);
console.log(Number("10px"));
console.log(parseInt("10px", 10));

What four lines are printed?

10Debugging investigation

The booking shows 2010 tickets

A booking form adds adult and child tickets. A family of 20 adults and 10 children should see 30 tickets, but the summary says 2010.

const adults = "20";    // from an input field
const children = "10";  // from an input field
const total = adults + children;
console.log("Total tickets:", total);

More cases in the Debugging Detective Laboratory

11Practical scenario

Form fields are text

The Tip Calculator reads the bill, tip percentage and number of people from input fields. Their values are strings, so the project converts them with Number() and checks for NaN before any calculation.

const billText = "80";
const bill = Number(billText);
console.log(Number.isNaN(bill) ? "invalid" : bill * 1.15);

12Knowledge check

1. What does this print?

console.log("5" + 3);
  • 8
  • 53
  • NaN
  • "53"

2. What does this print?

console.log(Number(""));
  • NaN
  • 0
  • undefined
  • An error

3. Which converts "19.99" to a number without losing the cents?

  • parseInt("19.99", 10)
  • parseFloat("19.99")
  • String("19.99")
  • Boolean("19.99")

4. What does this print?

console.log(typeof [1, 2, 3]);
  • array
  • object
  • list
  • undefined

5. Why does this print 1050 instead of 60?

const price = "10";
console.log(price + 50);
  • The numbers are too big
  • price is a string, so + joins the text
  • Math is needed for addition
  • The variable names are wrong

6. Both read a quantity from text. Which is clearer to a reader?

  • const q = +text;
  • const q = Number(text);
  • Both are equally clear to beginners
  • Neither converts

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the form total: Prints Tickets: 5; tickets is the number 5; Inputs stay strings
  • Read the measurements: Prints the values and types; width and weight are numbers
  • Validate an age field: Prints four validation results; Uses Number.isNaN
  • ex-010-01: output matches the documented expected output
  • ex-010-02: output matches the documented expected output
  • ex-010-03: output matches the documented expected output
  • ex-010-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-02-variables-values-and-types/lesson-010-type-conversion-and-type-checking/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • typeof names a value's type; arrays and null report "object".
  • Convert on purpose with Number, String and Boolean.
  • parseInt and parseFloat read numbers from the start of text.
  • + joins text; other arithmetic converts to numbers. Check for NaN and empty input.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation Explicit versus implicit conversion
Context: I am learning type conversion.
Task: Explain explicit and implicit conversion with six short examples.
Constraints: Beginner level, no objects.
Expected behaviour: I can predict + and - with mixed types.
Testing: End with four snippets to predict.
Code prediction Coercion puzzles
Context: I know Number, parseInt and parseFloat.
Task: Give me eight conversion expressions to evaluate.
Constraints: Include empty strings and units like px. Wait for answers.
Expected behaviour: Each has one answer.
Testing: Explain any I miss.
Debugging Text instead of numbers
Context: My form total prints 2050 instead of 70.
Task: Help me trace which values are strings.
Constraints: Ask me to log typeof for each value.
Expected behaviour: I find and convert the strings myself.
Testing: Suggest one test for empty input.
Exercise generation Input validation drills
Context: I finished the age validation exercise.
Task: Create two validation exercises for text inputs (price, quantity).
Constraints: Exact expected output for each input.
Expected behaviour: Each handles empty, invalid and valid input.
Testing: Include expected output.
Code review Conversion review
Context: My script reads five form values and calculates a total.
Task: Review where conversions happen and suggest converting once at input.
Constraints: No rewrites; list issues.
Expected behaviour: Each value is converted exactly once.
Testing: Point out any missing NaN check.