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.5Both functions read the number from the start of the string and stop at the first character that is not part of a number. If the string does not start with a number, they return NaN (Not a Number):
console.log(parseInt("5ab")); // Outputs: 5 (parses until invalid character)
console.log(parseFloat("5.2xyz")); // Outputs: 5.2 (parses until invalid character)
console.log(parseFloat("abc123")); // Outputs: NaN (no number at the start)Values that come from user input (like inp[0]) are always strings, so convert them with parseInt or parseFloat before doing math: otherwise + joins them as text instead of adding them.
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.
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 FalsePractice on your own: Online JavaScript compiler