In JavaScript, type conversion (also known as type coercion) is the process of converting a value from one data type to another. JavaScript performs automatic type conversion when operators are applied to values of different types, and explicit type conversion can also be done using built-in functions or operators. Here's an overview of type conversion in JavaScript:
JavaScript automatically converts values from one type to another when operators are applied to them. This is known as implicit type conversion or coercion.
Example:
let num = 10; // Number
let str = '20'; // String
let result = num + str;
console.log(result); // Output: '1020' (string concatenation)
In this example, the number 10 is implicitly converted to a string and concatenated with the string 20 , resulting in 1020 .
JavaScript provides built-in functions and operators for explicit type conversion. This allows you to convert values from one type to another intentionally.
a. String Conversion:
let num = 10;
let str = String(num);
console.log(str); // Output: '10' (string)
b. Number Conversion:
let str = '20';
let num = Number(str);
console.log(num); // Output: 20 (number)
c. Boolean Conversion:
let num = 0;
let bool = Boolean(num);
console.log(bool); // Output: false (boolean)
d. parseInt and parseFloat:
let str = '10';
let num = parseInt(str);
console.log(num); // Output: 10 (number)
let floatStr = '3.14';
let floatNum = parseFloat(floatStr);
console.log(floatNum); // Output: 3.14 (number)
JavaScript has truthy and falsy values, which can affect the outcome of conditional statements and type conversion.
Truthy Values:
Falsy Values:
Understanding type conversion in JavaScript is crucial for writing reliable and predictable code. It's important to be aware of how values are coerced in different contexts to avoid unexpected behavior.