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.5If 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
BeginnerGiven 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.5These functions parse until they encounter an invalid character:
parseInt("5ab"); // Returns: 5
parseFloat("5.2xyz"); // Returns: 5.2Type 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 belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False