JavaScript Type Conversions

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!
Learn via video course
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
By Mrinal Bhattacharya
Free
4.8
Enrolled: 1000
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
Mrinal Bhattacharya
Free
4.8
Enrolled: 1000
Start Learning

Type conversion in JavaScript is an algorithm that allows us to manipulate the function’s data types from one to another (such as string to a number, object to a boolean, and so on) which is required by the function or operator to work in the right way to give the expected results. Also, sometimes, the Javascript compiler automatically does these conversions and ensures that the function gets the valid inputs according to the operator used. We will dive deep into the concept and learn more about these conversions in this article.

Firstly, to get started with type conversions, we need to know that any calculation can be done among the same data types only. So what if we force JavaScript to do any such operations, like adding a number to a string? well in such cases, the javascript compiler, by default, converts the number to the string format and then concatenates them both, this is what type conversions are.

Let’s now understand these conversions with a few examples:

Implicit Type Conversion

Implicit Type Conversions are the conversions of one data type into another data type (ensuring that operations are done among same data types) for the operators or functions to work correctly.

JavaScript automatically converts one data type to another (to the right type). These conversions are also known as type coercion in Javascript.

In the instance above, let’s now talk about where these conversions occur in Javascript with the help of a few examples:

One operator that does not trigger implicit type coercion is ===, which is a strict equality operator, whereas the loose equality operator == does both comparison and conversion if need

Explicit Type Conversions

Explicit Type Conversions are the conversions that are manually performed by the developer in the source code in order to get the required changes and to undo the errors done by the implicit type conversions. Such conversions are also referred as typecasting in JavaScript.

Now, you might think that where Implicit type conversions fail to give required changes, well to understand this let’s take an example: you might remember that when we use the prompt() function, it always returns a string to the developer console, this may lead errors in our function as :

In this example, we have seen how implicit type conversions can leads to a huge error/bug in a codebase, and to avoid such bugs we need to change the data type of value of pensInBag from string to a number manually, for which we can use Number() function. Similarly, for other manual conversions we can use Boolean(), String(), Number(), parseInt(), etc functions.

Explicit conversions can rescue us from such errors caused by implicit conversions, let’s see how:

Here, we will use the Number() function to change the data type of value of pensInBag from a string to a number so as to get the correct output.

Here are some other examples of explicit type conversions in primitive values:

Types of Data Conversions in JavaScript

The different types of type conversion in JavaScript are:

  • String conversions
  • Numeric conversions
  • Boolean conversions
  • Symbol conversions

Let’s now first begin with type conversions for Primitives.

String Conversions

The conversion of a data type into a string is something known as String Conversion. To explicitly convert a data type into a string, we just need to apply the String() function, and implicit string conversion can be triggered by the use of + binary operator when one operand is a string.

All primitive values are converted to strings naturally, as you might expect:

Explanation

From the above example, we have conquered that the + operator tends to convert the value of different data types into a string when there is an addition between a string and an operand of a different data type.

Numeric Conversions

Now, it’s time for Numeric conversions, likewise string conversion, we use the Number() method to convert strings, booleans, and other numeric expressions into a number Explicitly.

Implicit numeric conversion is tricky because it is triggered in many cases :

  • Comparision operators (>, <, =>, <=)
  • arithmetic operators ( `+`  / % ).
  • Bitwise operators ( | & ^ ~)
  • unary + operator
  • loose equality operator == (incl. !=).

Let’s now look at some of the examples of numeric conversions:

Points to Remember:

  • In an expression, when we apply == operator to null or undefined, numeric conversions does not happen. Also, null is equal to null or undefined, and cannot be equal to anything else.
  • To get an integer value from a given value, we use the parseInt() method :
  • According to operator precedence, the + operator has left-to-right associativity, so if we have an expression 2 + 3 + '4' + 'number' the the operation is done in the following way :

Boolean Conversions

Conversion of an expression into a boolean is known as boolean conversion. This conversion can be either done explicitly by the Boolean() Function, or implicitly in logical contexts (like in if/else ) or triggered by the use of the logical operators (||, &&, !).

For instance:

Logical operators such as || and && do boolean conversions internally but return the value of original operands even if they are not boolean. As in the above example :

Points to Remember -

  • We know that there are namely two boolean results : true or false, so it's just easier to remember the list of false values.

All other values except these, are truthy values, including object, array, date, and so on. Even all Symbols, Empty objects, and arrays are truthy values.

Symbol Conversions

Symbol conversion is a bit tricky and can only be converted explicitly, but not implicitly. Specifically, symbols cannot be coerced into strings or numbers so that they cannot be used accidentally used as properties that would be otherwise expected to behave as a symbol.

When we use console.log() to show the outputs of the symbols, it works because console.log() calls String() on the symbols to create useful results.

For instance:

If you try to add a symbol directly with a string, it will throws a TypeError as :

Concatenating mySymbol to a string requires mySymbol to be first converted into a string, and an error is thrown when coercion is detected, preventing its use in this manner.

Similarly, you cannot coerce a symbol to a number, all mathematical operators throw an error when used with a symbol.

The above example attempts to divide a symbol by 2 but throws an error regardless of the operator used.

Type Conversion in Objects

So far, we have learned about type conversion for primitives. Now when it comes to objects and the compiler encounters expressions like [2] + [5, 3], first it needs to convert an object to a primitive, which is then converted into a boolean, string, or a number.

Both numeric and string conversion make use of two methods of the input object: valueOf and toString. Both methods are declared on Object.prototype and thus available for any derived types, such as Date, Array, etc.

JavaScript Type Conversion Table

In the table below are some of the most common JavaScript values conversion to Number, String, and Boolean :point_down:

ValueString conversionNumber conversionBoolean conversion
20'20'20true
'20''20'20true
false'false'0false
true'true'1true
0'0'0false
'0''0'0true
NaN'NaN'NaNfalse
null'null'0false
undefined'undefined'NaNfalse
[]''0true
""""0false
[23]'23'23true
[10,23]'10,23'NaNtrue
" "' '0true
['fun']'fun'NaNtrue
['fun','enjoy']'fun,enjoy'NaNtrue
function(){}'function(){}'NaNtrue
{}'[object Object]'NaNtrue
Infinity'Infinity'Infinitytrue
-Infinity'-Infinity'-Infinitytrue

Conclusion

  • Type conversion in JavaScript is the conversion of one Data type to another as required for the function to work in the right way.
  • The major difference between implicit and explicit type conversion is that the implicit conversions are automated by the JavaScript compiler behind the scenes while explicit ones are done manually by us.
  • It is highly recommended to use explicit type conversions and avoid dependency on implicit type conversions as much as possible, this will help to avoid unnecessary bugs and errors in the code.
  • Explicit conversion has a major role in manipulating data types in the way we want for the specific function.