Start learning free

LESSON 15 OF 671 · VARIABLES

Type Conversion in JavaScript

Lesson

In JavaScript, every value has a type: number, string, boolean, and so on. Sometimes you need to convert a value from one type to another. This is called type conversion.

Use these functions to convert between types:

String(x)      // converts x to a string
Number(x)      // converts x to a number
parseInt(x)    // converts x to an integer (drops decimals)
parseFloat(x)  // converts x to a float

Here are some examples:

let score = 42;
let scoreStr = String(score);        // "42"  (number → string)

let weight = 70.8;
let weightInt = parseInt(weight);    // 70    (float → integer, decimal dropped)

let count = "100";
let countInt = parseInt(count);      // 100   (string → integer)

Note that parseInt drops the decimal part - it does not round.

parseInt(9.99)  // → 9
parseInt(3.1)   // → 3

Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use String() and parseInt().

STEP 1 OF 3
    Ctrl + Enter to check