Skip to main content

JavaScript Type Conversions (Live Playground)

Type conversion, or type casting, is the process of converting a value from one data type to another. In JavaScript, type conversions can be performed implicitly by the language itself or explicitly using built-in functions or operators. In this tutorial, we'll explore various type conversions in JavaScript and learn how to perform them effectively using explicit and implicit methods.

Implicit Type Conversions

JavaScript automatically performs implicit type conversions when needed, such as when using the + operator with a string and a number.

Example:

const num = 42;
const str = 'Hello, world!';
const result = str + num;

console.log(result); // Output: Hello, world!42

In the example above, the num variable is implicitly converted to a string before concatenation with the str variable.

Live Playground, Try it Yourself

Explicit Type Conversions

JavaScript provides several built-in functions and operators to explicitly perform type conversions when necessary.

String to Number

You can convert a string to a number using the Number() function or the parseInt() and parseFloat() functions.

Example:

const str1 = '42';
const num1 = Number(str1);
console.log(num1); // Output: 42

const str2 = '42.5';
const num2 = parseFloat(str2);
console.log(num2); // Output: 42.5
Live Playground, Try it Yourself

Number to String

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

Example:

const num = 42;
const str1 = String(num);
console.log(str1); // Output: '42'

const str2 = num.toString();
console.log(str2); // Output: '42'
Live Playground, Try it Yourself

Boolean Conversions

You can convert a value to a boolean using the Boolean() function or the !! (double NOT) operator.

Example:

const truthyValue = 'Hello, world!';
const bool1 = Boolean(truthyValue);
console.log(bool1); // Output: true

const bool2 = !!truthyValue;
console.log(bool2); // Output: true
Live Playground, Try it Yourself

Conclusion

Understanding type conversions in JavaScript is crucial for working with different data types effectively in your programs. JavaScript can perform implicit type conversions automatically, but it's often better to use explicit type conversions for clarity and to avoid unexpected behavior. Familiarize yourself with the built-in functions and operators for performing explicit type conversions, such as Number(), String(), and Boolean().