Type coercion in JavaScript

The process of transforming one data type into another is known by a variety of names, including type coercion, type conversion, typecasting, and type juggling. This procedure is a key idea in computer science and is present in practically all programming languages.

Even though JavaScript is regarded as one of the simpler programming languages for novices, it can still be annoying when developers expect JavaScript to perform one action but receive a different response.

Even though the ECMAScript Language Specification standard is given to developers to aid in navigating them through these difficulties, failure to read and comprehend the specification standard can make dealing with type coercion in JavaScript more frustrating.

JavaScript's type coercion is an illustration of how the language might yield unexpected outcomes when we don't fully understand how it operates. Anyone who has written even a small amount of JavaScript code can attest to the difficulty of type coercion.

The reason we discuss why type coercion behaves as it does is because many legacy products and code depend on older versions of JavaScript, even if the code examples we discuss in this article may appear to be flaws that a version upgrade could remedy.

Types in JavaScript

We can refer to JavaScript as an untyped language, which means that it has no static types. However, the prominent myth that JavaScript doesn’t have types is false.

JavaScript has seven primitive types:

1) string

2) number

3) Boolean

4) undefined

5) null

6) Symbol

7) BigInt

Variables in JavaScript don’t have types, however. Whenever we use the typeof operator to return a variable type, we return the variable’s value type.

Now that we have cleared up a few misconceptions about JavaScript and types, we can learn more about type coercion and how it works in JavaScript.

Type coercion

Type coercion in JavaScript only coerces to the string, number, and Boolean primitive types. There’s no way in JavaScript to coerce a value type to object or function.

JavaScript has two characterized forms of coercion: implicit coercion and explicit coercion.

Implicit coercion happens when JavaScript coerces the value type to the expected type under the hood. This type of coercion happens without the developer noticing.