Menu
Coddy logo textTech

Type Conversion - Part 1

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 30 of 77.

To convert between different data types in JavaScript, we need to use type conversion.

JavaScript supports both implicit and explicit type conversion. Let's focus on the most common explicit conversion methods part 1:

parseInt and parseFloat

// String to Number conversion using parseInt and parseFloat
let str = "42";
let num1 = parseInt(str);    // Converts to integer
let num2 = parseFloat("42.5");  // Converts to floating-point

console.log(num1);  // Outputs: 42
console.log(num2);  // Outputs: 42.5

If the string contains an invalid number, these functions behave differently:

console.log(parseInt("5ab"));   // Outputs: 5 (parses until invalid character)
console.log(parseFloat("5.2xyz")); // Outputs: 5.2 (parses until invalid character)

It is important to use the right type because it can affect the output.

Concatenating two strings: "5" + "5" == "55"

Adding two numbers: 5 + 5 == 10

Understanding type conversion is essential for writing reliable JavaScript code and avoiding unexpected results in your programs.

challenge icon

Challenge

Beginner

Given two strings var1 and var2.

Cast them to a float and print the multiplication of the two.

Cheat sheet

JavaScript supports explicit type conversion using parseInt() and parseFloat():

let str = "42";
let num1 = parseInt(str);        // Converts to integer: 42
let num2 = parseFloat("42.5");   // Converts to floating-point: 42.5

These functions parse until they encounter an invalid character:

parseInt("5ab");      // Returns: 5
parseFloat("5.2xyz"); // Returns: 5.2

Type conversion is important because different data types behave differently:

  • String concatenation: "5" + "5" == "55"
  • Number addition: 5 + 5 == 10

Try it yourself

let var1 = inp[0] // Don't change this line
let var2 = inp[1] // Don't change this line

// Write code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals