Junior
Mis on tüübi teisendamine?
sobes.tech AI
Vastus AI-lt
Type conversion is the process of transforming the value of one data type into another.
In JavaScript, there are two types of conversions:
- Explicit conversion: performed using constructor functions or special methods. The developer explicitly indicates that they want to change the data type.
- Implicit conversion: occurs automatically by the JavaScript engine in certain situations, such as when using comparison or arithmetic operators between values of different types.
Examples of explicit conversion:
// Converting a string to a number
let num = Number("123");
// Converting a number to a string
let str = String(456);
// Converting a number to a boolean
let bool = Boolean(0); // false
let bool2 = Boolean(1); // true
Examples of implicit conversion:
// Adding a string and a number - the number is implicitly converted to a string
let result = "Hello " + 5; // "Hello 5"
// Comparing a string and a number - the string is implicitly converted to a number
let compare = "10" == 10; // true
// Multiplying a string and a number - the string is implicitly converted to a number
let product = "5" * 2; // 10
Understanding type conversion is crucial to prevent unexpected behavior in code. Implicit conversion can be a source of errors, so in some cases, it is better to use explicit conversion for greater clarity and predictability.