Automatic Type Conversion in JavaScript

In this article, I shall talk about the automatic type conversion of JavaScript interpreter. If you are new to JavaScript programming, you might have overlooked some of the conversions that can break your code very easily.

JavaScript is the king of itself. It sometimes does whatever it likes to do, and that too in very odd way, yielding very odd result.

Odd Nature of JavaScript Conversions

Let me demonstrate the Automatic Type conversion abnormality by giving you some examples.

Example 1:

console.log(200*null); // What do you think will be the output of this?
// Output -> 0

Did you really expect the output 0? If the answer is No, then you are not alone. Most of the programmers think that the output would be undefined or there may be an error, but it is not the case. Now let us look another odd behavior of JavaScript interpreter.

Example 2:

console.log("100" - 10);
// Output -> 90; however,
console.log("100" + 10);
// Output -> 10010

In the above snippet of code, as you can see there is an extremely odd behavior occurred.

In the first line, JavaScript interpret the - symbol as the negative sign, and subtracts 10 from 100. In console.long("100" + 10), JavaScript took the symbol + as the concatenation symbol for the Strings, and outputs 10010.

Example 3:

console.log("ten" * 2)
// Output -> NaN

Example 4:

console.log(false == 0)
// Output -> True

Now let us see how JavaScript does all of these conversions. In JavaScript terms, this conversion is known as type coercion.

Type Coercion

Type coercion means that the two values compared only after converting them into a common type.

It means that if one variable has the type Integer and the second variable has the type String, JavaScript will first try to guess and convert the types, either to Integer or String, and after that it will compare the contents of those two variables.

Let us take an example:

console.log("ten" * 2)
// Output -> NaN

When something that doesn’t map to a number in an obvious way (such as ten or undefined) is converted to a number, you get the value NaN. Further arithmetic operations on NaN keep producing NaN, so if you find yourself getting one of those in an unexpected place, look for accidental type conversions.

Summary

We have explored some bizarre cases of automatic type conversions in JavaScript. The new concept type coercion was also explained in this article, which is kind of the soul of automatic type conversions in JavaScript. That's it for this article!

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?