About Lesson
What is Type Coercion and Conversion
JavaScript is dynamically typed, meaning a variable’s data type is determined automatically, but this can sometimes lead to unexpected results. This is where type coercion and conversion come into play.
1. Implicit Conversion (Type Coercion):
JavaScript automatically converts types behind the scenes, which can sometimes produce unexpected results.
Example:
JavaScript
console.log(5 + "10"); // Output: "510" (Number is coerced to String)
console.log("5" - 2); // Output: 3 (String is coerced to Number)
2. Explicit Conversion:
You can explicitly convert one type to another using functions like String(), Number(), or Boolean()..
Example:
JavaScript
let num = "10";
let convertedNum = Number(num); // Converts string to number
console.log(convertedNum + 5); // Output: 15