JavaScript : Type Conversion

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:

1. Implicit Type Conversion (Coercion):


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 .

2. Explicit Type Conversion:


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:

  • String(value) : Converts a value to a string.

let num = 10;
let str = String(num);
console.log(str);   // Output: '10' (string)

 

b. Number Conversion:

  • Number(value) : Converts a value to a number.


let str = '20';
let num = Number(str);
console.log(num);   // Output: 20 (number)

 

c. Boolean Conversion:

  • Boolean(value) : Converts a value to a boolean

let num = 0;
let bool = Boolean(num);
console.log(bool);   // Output: false (boolean)

 

d. parseInt and parseFloat:

 

  • parseInt(string) : Parses a string argument and returns an integer.
  • parseFloat(string) : Parses a string argument and returns a floating point number.


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)

 

3. Truthy and Falsy Values:


JavaScript has truthy and falsy values, which can affect the outcome of conditional statements and type conversion.

Truthy Values:

 

  • Non-empty strings ( hello )
  • Numbers other than 0 ( 10 , 3.14 )
  • Objects (including arrays and functions)
  • true

Falsy Values:

 

  • Empty string (`''`)
  • 0
  • null
  • undefined
  • NaN
  • false

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.