Member-only story

Coercion in Javascript

#5 of the 40 Essentials of Javascript — Coercion

Indy Seh
2 min readJan 12, 2023
Photo by Blake Connally on Unsplash

In JavaScript, Coercion is the process by which a value of one data type is converted or coerced into a value of a different data type. It is an essential concept within the JavaScript language since JavaScript is a loosely typed language, which means that values are automatically converted to the target data type without explicit type conversion. This is done to avoid data loss or unexpected errors when attempting to perform operations on non-matching data types.

Coercion in JavaScript can be divided into two categories:

  • Implicit Coercion
  • Explicit Coercion

Explicit Coercion

Explicit coercion is when you deliberately force a value to conform to another data type, in other words, When type conversion is explicitly done in the code by the developer using inbuilt methods for type conversion. This is done by using functions to convert one type of data into another, such as parseInt(), parseFloat(), Boolean(), and so on.

Let's understand it using examples.

// The following code converts a string, "1234", to a number
parseInt("1234");

2. The following code converts a number, 456, to a string:
String(456);

3. The following code converts a…

--

--

Indy Seh
Indy Seh

Written by Indy Seh

Python | Go | Javascript | Typescript | Frontend | Backend

No responses yet

Write a response