How to Avoid JavaScript Type Conversions

JavaScript performs implicit conversions between data types. Let’s find out how to avoid it. For example, take a look at the condition below.

Even though []==0 results in true , the if condition has not executed according to that result. Ever wondered why that is?

This article is all about explaining how these value comparisons work and what affects them. Before diving into that explanation, there is a concept you should be familiar with; Type Conversions.

What are JavaScript Type Conversions?

This is also known as Type Coercion. For those of you who aren’t familiar with this concept, it is simply the automatic conversion of values from one data type to another.

This occurs because JavaScript is a weakly typed language.

Let’s look at an example to make it clearer.

In this example, the two variables defined are of two types; String and Number. However, when we compare those using == (Abstract Equality Comparison / Non-strict comparison), it results true . The reason behind this is when we compare these two using == JavaScript will automatically try to convert the String type to Number type to produce the result. It is a forceful type of conversion.

There are many types of coercion in JavaScript.

  • Number conversions

  • String conversions

  • Boolean conversions

  • Type conversion for objects, etc.

Here are some examples.

Is type coercion always good?

Well, in a scenario as above, the type conversion does no harm. However, there are many instances where type coercion can cause problems.

Let’s have a look at an example.