JavaScript Guide: Type Conversion & Coercion

JavaScript Guide: Type Conversion & Coercion

In this second chapter of JavaScript guide, we’re demystifying type conversion. Curious about how to seamlessly switch between data types? We’ll explore both implicit and explicit conversions, giving you the tools to handle data flexibly in your code. Ready to level up your JavaScript skills? Let’s get started!

Summary

  1. What is Type Conversion?
  2. Implicit Type Conversion (Type Coercion)
  3. Explicit Type Conversion (Type Casting)

What is Type Conversion?

In the world of JavaScript, Type Conversion is the process of transforming data from one type to another, adapting to the ever-shifting needs of your code.

But why does it matter? Imagine you have a number, and suddenly, it needs to work with a string. How do you make this duet happen without causing chaos in your code? That’s where Type Conversion swoops in.

As already mentioned in previous chapter JavaScript Guide: Data Types, values in JavaScript can be of different types: boolean, number, string, bigInt, symbol, null, undefined or Object.

There are two main types of Type conversion in JavaScript:

  1. Implicit Type Conversion — automatically done during code execution by JavaScript engine. It is usually done when some operation is done on operands of different data types.
  2. Explicit Type Conversion — done manually by humans.

Implicit Type Conversion (Type Coercion)

Implicit Type Conversion or Type coercion in JavaScript is the automatic conversion of one data type to another. This happens when an operator or function requires a certain type, but the actual data type is different.

So, if you’re trying to apply operator + on 2 operands, one string and other number, the implicit type conversion will do its job and make it possible to use this operator, result will be a concatenation of string and number converted to string. Here’s a simple example of this:

Article content

As you can see, numberVar is a number, and stringVar is a string. When the + operator is used, JavaScript coerces the number into a string and performs string concatenation instead of numerical addition. The result is the string "1020."

Let’s see the operands that cause implicit type conversion of data in JavaScript:

Loose equality operator

JavaScript provides two equality operators: the double equality operator (== and !=), known as the loose equality operator, and the triple equality operator (=== and !==), known as the strict equality operator. These operators are used to compare the equality of values.

The loose equality operator performs a loose check, focusing solely on whether values are equal. It converts operands to numbers unless they’re null or undefined. Of course, if operands are of the same type there is no need to convert them to numbers. Unlike the strict equality operator, it doesn’t prioritize types — only the values themselves are considered. Let’s have a look:

Article content

What happens here? Well, coercion duh… When the loose equality operation is performed, the operand b is implicitly converted from string to number and then the comparation of both number values is done. Since the number value of operand a is 10, and number value of operand b is also 10, the result of operation is true.

Article content

Here, JavaScript will coerce the boolean bool1 to a number in order to perform the loose equality check. The coercion rules are such that false is coerced to 0 during numeric operations. So, in this case bool1 is loosely equal to num1, since the numeric values of both are 0. In the second example, bool2is converted to number 1 and the result of loose equality is false, since 1 is not equal to 6. Here are some other logical examples:

Article content

Here are some cases with null and undefined that you should keep in mind:

Article content

And now some special cases:

Article content

On the other side, the Strict equality operator or triple equality operator (=== and !==) conducts a strict check, thoroughly examining both the values and their types. Unlike the loose equality operator, there is no type coercion happening here, ensuring precise and expected results.

Article content

The values of operand a and operand b are the same, but their data types are different — number and string, so the strict equality operator returns false. There is no need for type coercion.

Comparison operators

As you already know, comparison operators are used to compare two values and they are: >, <, ≥ and ≥. They coerce values to numbers.

Article content

Explanation: JavaScript performs implicit type conversion when comparing a and b. So b is converted to a number for the comparison. Now, it compares the numerical values of a and b. Result: a > b is false because 5 is not greater than 10. Similarly, a < b is true because 5 is less than 10.

Logical operators

Logical operators are used to determine if an expression evaluates to true or false. Operators are: && (AND), || (OR) and ! (NOT). They coerce values to boolean type.

Article content

Unary operators

Unary operators are operators that only operate on one operand. One common unary operator in JavaScript is the + operator, which is used for converting its operand to a number. Unary operators are: +, ++, -, - -.

Article content

Arithmetic operators

They are used to perform arithmetic operations over operands: + (addition), (subtraction), * (multiplication) and / (division). Arithmetic operands coerce operands to numbers, except for + operator (if one operand is of type string, the operand + is used as concatenation and other operand is coerced to string).

Article content

When the * operator is encountered, JavaScript attempts to perform a mathematical operation. Since the operand str is a string and the other num is a number, JavaScript implicitly coerces the string to a number. So str is converted to number 5, and the result of multiplication is number 50.

Bitwise operators

They treat operands as sets of 32-bit binary digits, so the operations are done on individual bits. They coerce operands to numbers. They work on the binary representation of integers. If an operand is not an integer, it will be converted to one before the operation. Bitwise operators are: | (bitwise or), & (bitwise and), ^ (xor) and ~ (bitwise not).

Article content
🧐 Can I prevent Type Coercion somehow in JavaScript?

Yes, don’t worry! Shielding your code from type coercion in JavaScript involves vigilance regarding variable and operand data types. Utilize type conversion functions when needed. Opt for the strict equality operators (=== and !==) instead of their loose counterparts (== and !=) during value comparisons. If you remember, strict equality operators ensure that compared values are not only identical in value but also share the same type, preventing implicit type coercion!


Explicit Type Conversion (Type Casting)

Explicit type conversion in JavaScript, also known as Type Casting, is the process of manually converting a value from one data type to another. This is done using built-in functions or operators that are specifically designed for type conversion. You use Type Constructors to explicitly convert types. Unlike implicit type conversion, which happens automatically during certain operations, explicit type conversion gives you control over the conversion process.

There are 3 types of explicit conversion:

  1. Conversion to Boolean
  2. Conversion to Number
  3. Conversion to String

Conversion to Boolean

Here are examples of explicit conversion to Boolean data type using Boolean(value) constructor:

Article content

Conversion to Number

Here are examples of explicit conversion to Number data type using Number(value) constructor:

Article content

Conversion to String

Here are examples of explicit conversion to String data type using String(value) constructor:

Article content

There are some specific functions that JavaScript provides us so we can do the type conversion:

  • value.toString([radix]) method — coverts the given number valueand returns its corresponding string representation. The optional argument radix represents the base of number value and it can take values from 2 to 36 (default is 10).

Article content

Object.toString() method — returns a string representation of an Object, and that’s the [object Object] string. Mmm, that’s not helpful at all, right? Well, the toString() method is meant to be overridden to accomplish the desired Custom Type Conversion logic. Let’s have a simple example:

Article content
Example of overriden toString() method

Some Objects have the toString() method already overridden. In the previous example, value.toString([radix]) method is actually an overridden Object.toString() method but for Number type. String object has its own toString() method overridden, also Boolean too. Let’s have a quick look:

Article content

  • parseInt(string [, radix]) — parses a string argument of type string and returns an Intiger value with a specified radix which is optional argument that can have values from 2 to 36 (defaults to 10). If the string argument can’t be converted to an Integer, the result is a NaN value.

Article content

  • parseFloat(string) — parses a string argument of type string and returns a Floating point number. If the string can’t be converted to Floating point number, the result is a NaN value.

Article content

Conclusion

In conclusion, navigating the nuances of JavaScript’s type conversion and coercion is crucial for writing robust and predictable code. Understanding how values are converted, both implicitly and explicitly, empowers developers to handle data effectively. Whether you’re converting between types for operations or dealing with comparisons, a solid grasp of these concepts is essential for mastering JavaScript. Happy JavaScripting!

Additional resources:

To view or add a comment, sign in

More articles by Mila M.

  • JavaScript Guide: Data Types

    Hey there, coding enthusiasts! 👋 As you already know, in the coding word, understanding data types is crucial. From…

  • Apex Integration Services Guide: RESTful service

    Introduction In the world of Salesforce, where businesses manage customer relationships, making sure that Salesforce…

  • Design Patterns in Apex

    Introduction In the world of Salesforce development, efficiency and scalability are really important. Design patterns…

    2 Comments

Others also viewed

Explore content categories