JavaScript Type Conversion

In JavaScript, type conversion refers to the process of converting a value from one type to another. JavaScript is a loosely-typed language, which means types are automatically converted in some cases, and explicit conversion is often needed.

1. Implicit Type Conversion

Implicit type conversion, also known as type coercion, occurs when JavaScript automatically converts types during operations. This can lead to unexpected results if not properly managed.


// Examples of implicit type conversion
console.log('5' + 1); // Output: "51" (string concatenation)
console.log('5' - 1); // Output: 4 (string to number conversion)
console.log(1 + true); // Output: 2 (boolean to number conversion)
console.log(null + 1); // Output: 1 (null to number conversion)
console.log('5' == 5); // Output: true (string to number conversion for comparison)

            

2. Explicit Type Conversion

Explicit type conversion is done manually using built-in functions to convert values to specific types.

2.1. Converting to String

You can convert a value to a string using the `String()` function or the `.toString()` method.


// Converting to string
let num = 123;
let str = String(num);
console.log(str); // Output: "123"

let bool = true;
let strBool = bool.toString();
console.log(strBool); // Output: "true"

            

2.2. Converting to Number

To convert a value to a number, use the `Number()` function or the unary `+` operator. Be cautious with `parseInt()` and `parseFloat()` as they parse strings into numbers.


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

let bool = true;
let numBool = +bool;
console.log(numBool); // Output: 1

let invalidStr = 'abc';
let numInvalid = Number(invalidStr);
console.log(numInvalid); // Output: NaN

let strFloat = '12.34';
let floatNum = parseFloat(strFloat);
console.log(floatNum); // Output: 12.34

            

2.3. Converting to Boolean

To convert a value to a boolean, use the `Boolean()` function or double negation (`!!`). In JavaScript, values are considered "truthy" or "falsy".


// Converting to boolean
let str = 'hello';
let bool = Boolean(str);
console.log(bool); // Output: true

let zero = 0;
let boolZero = !!zero;
console.log(boolZero); // Output: false

let nonEmptyStr = 'non-empty';
let boolStr = Boolean(nonEmptyStr);
console.log(boolStr); // Output: true