What is Type Coercion and Type Casting in JavaScript?

Written by kirmani | Published 2023/05/25
Tech Story Tags: javascript | job-interview | data-types | coercion | programming-tips | programming | software-development | type-conversion

TLDRIn programming languages, data is classified into various types, such as integers, strings, floating-point numbers, and booleans. The ability to convert or coerce data from one type to another is essential for performing operations, manipulating data, and ensuring the compatibility and consistency of data within a program. Type coercion refers to the automatic conversion of data types that occurs in JavaScript when different types of data are used together in an operation.via the TL;DR App

Type coercion and type casting are fundamental concepts in programming that involve the conversion of data from one type to another. In programming languages, data is classified into various types, such as integers, strings, floating-point numbers, and booleans. The ability to convert or coerce data from one type to another is essential for performing operations, manipulating data, and ensuring the compatibility and consistency of data within a program.

Type Coercion:

Type coercion refers to the automatic conversion of data types that occurs in JavaScript when different types of data are used together in an operation. For example, if a number and a string are added together, JavaScript will automatically convert the number to a string to perform the operation.

const num = 5;
const str = "3";
console.log(num + str);  //output: "53"

In the example above, the number 5 is automatically converted to the string “5” so that it can be concatenated with the string “3” to give the output “53”. Some other examples of type coercion include:

  • Using the == or != operators for comparison, which perform type coercion before making a comparison
  • Using the unary plus (+) operator before a value will perform type coercion to Number. However, the + sign can only appear once and must not be followed by whitespace.

For e.g.:

const x = "5";
const y = +x;
console.log(typeof y); // output: number

It is often believed that using the unary + operator at the start of a value in JavaScript is a shorthand for the Number function. However, this is not the case. Both the unary + operator and Number function use the same algorithm to convert a string to a number, but there are subtle differences.

For example, while + will throw a TypeError when encountering a BigInt , Number() will return the number value of a BigInt but with a possible loss of precision. Coercion also happens if you use unary negation (-) operator before a string the same way.

  • Using the if statement, which will coerce a value to a boolean before making a comparison

  • Using the &&, || and ?: operators, which will coerce the value to a boolean before performing the operation.

Type casting:

On the other hand, type casting refers to the explicit conversion of data types. This is done using casting functions such as Number(), String(), Boolean() and Symbol()

const str = '5';
const num = Number(str);
console.log(num); //output: 5

In this example, the variable num is of type number, but we explicitly converted it to a string by using the String() function. Let’s take a look at several type casting functions in JavaScript, along with example code to demonstrate their use:

  • Number(): The Number() function is used to convert a non-numeric value into a numeric value. For example, if you want to convert a string value of “10” into a number, you would use the Number() function like this:
const x = "5";
const y = x+10
const z= Number(x)+10;
console.log(y); // output: 510
console.log(z); // output: 15

  • parseInt(): The parseInt function is used to convert a value into an integer. It is different from Number() and parseFloat() as it ignores any value after decimal. For example:
const intValue = parseInt("3.14");
console.log(intValue); // Output: 3

  • parseFloat(): The parseFloat() function is used to convert a string value into a floating-point number. It is very similar to Number() except for some cases. Lets see the example below to see how parseFloat() compares to parseInt() and Number():
console.log(parseInt('22.5')); // Output: 22
console.log(parseFloat('22.5')); // Output: 22.5
console.log(Number('22.5')); // Output: 22.5

console.log(parseInt('070')); // Output: 70
console.log(parseFloat('070')); // Output: 70
console.log(Number('070')); // Output: 70

console.log(parseInt('1234blue')); // Output: 1234
console.log(parseFloat('1234blue')); // Output: 1234
console.log(Number('1234blue')); // Output: NaN

console.log(parseInt('0xFF')); // Output: 255
console.log(parseFloat('0xFF')); // Output: 0
console.log(Number('0xFF')); // Output: 255

console.log(parseInt("10 20 30")); // 10
console.log(parseFloat("10 20 30")); // 10
console.log(Number("10 20 30")); // NaN

  • String(): The String() function is used to convert a non-string value into a string value. The below examples show how you can use String() function to convert different types of values to string:
const num = 10;
console.log(String(num)); // "10"

const bool = true;
console.log(String(bool)); // "true"

const obj = {name: "John"};
console.log(String(obj)); // "[object Object]"

const arr = [1, 2, 3];
console.log(String(arr)); // "1,2,3"

const date = new Date();
console.log(String(date)); // "Sun Jan 29 2023 18:52:01 GMT+0000 (Coordinated Universal Time)"

  • Boolean(): The Booleanfunction is used to convert a non-boolean value into a boolean value. For example, if you want to convert a number value of 0 into a boolean, you would useBoolean()like this:
let value = 0;
console.log(Boolean(value)); // false

value = "hello";
console.log(Boolean(value)); // true

value = undefined;
console.log(Boolean(value)); // false

value = {};
console.log(Boolean(value)); // true

value = -1;
console.log(Boolean(value)); // true

That’s it, folks. I hope this article helped you understand the ins and outs of type conversion in JavaScript. You now have a solid grasp on how to cast your variables to different types explicitly(type casting) as well as how Javascript does it implicitly(type coercion).

Keep practicing and experimenting with these functions to master them. Don’t forget to like, share, follow, and comment any questions you may have. Happy coding!

Pro Tip:

Use strict equality comparison === instead of abstract equality comparison ==. Avoid relying on JavaScript's implicit type coercion, especially in arithmetic operations, and always use type casting where necessary.

Also published here.


Written by kirmani | I'm a highly experienced SE with diverse skills. I stay up-to-date with the latest tech and love sharing knowledge
Published by HackerNoon on 2023/05/25