Junior
What is type casting?
sobes.tech AI
Answer from AI
Type casting is the conversion of a value from one data type to another.
In JavaScript, there are two types of casting:
- Explicit casting: performed using constructor functions or special methods. The developer explicitly indicates the desire to change the data type.
- Implicit casting: occurs automatically by the JavaScript engine in certain situations, such as when using comparison operators or arithmetic operators between values of different types.
Examples of explicit casting:
// Convert string to number
let num = Number("123");
// Convert number to string
let str = String(456);
// Convert number to boolean
let bool = Boolean(0); // false
let bool2 = Boolean(1); // true
Examples of implicit casting:
// Concatenating a string and a number - implicit conversion of number to string
let result = "Hello " + 5; // "Hello 5"
// Comparing a string and a number - implicit conversion of string to number
let compare = "10" == 10; // true
// Multiplying a string and a number - implicit conversion of string to number
let product = "5" * 2; // 10
Understanding type casting is critical for preventing unexpected code behavior. Implicit casting can be a source of errors, so in some cases, explicit casting is preferred for greater clarity and predictability.